Angular mat-autocomplete : How to display the option name and not the value in the input

firasKoubaa picture firasKoubaa · Mar 26, 2019 · Viewed 10.5k times · Source

I'm using the mat-autocomplete widget under my Angular app :

    <mat-form-field class="col-md-3" color="warn">
                <input type="text"
                       id="libelleShop"
                       #inputSelectShop
                       placeholder="Selectionner la boutique"
                       matInput
                       formControlName="libelleShop"
                       ngDefaultControl
                       [matAutocomplete]="auto">
                <mat-autocomplete #auto="matAutocomplete"" 
               (optionSelected)="onShopSelectionChanged($event)">
                  <mat-option *ngFor="let shop of shopData" [value]="shop.value">
                    {{shop.name}}
                  </mat-option>
                </mat-autocomplete>
   </mat-form-field>

my Shop data is like this :

shopData = [
    {name: 'AAA' , value :'11'},
    {name: 'BBB', value :'22'},
    {name: 'CCC', value : '33'}
  ];

Like this - options are displayed by name , but when selection the input displaysit by the value not the name.

Knowing that i need the value for other treatment and i won't change the [value] in the mat-automplete.

How may i take reference for the name to the input ??

Suggestions ??

Answer

Alex picture Alex · Mar 26, 2019

You can use the displayWith attribute of Mat autocomplete and pass in a function that will return the desired formatted string.

In your example:

displayFn(shop: Shop): string {
  return shop.name;
}
<mat-autocomplete #auto="matAutocomplete"" (optionSelected)="onShopSelectionChanged($event)" [displayWith]="displayFn">
    <mat-option *ngFor="let shop of shopData" [value]="shop.value">
      {{shop.name}}
    </mat-option>
  </mat-autocomplete>