When I select an item in the following matAutocomplete formControl, I always get the ID, instead of the value, shown in the drop-down.
When I change [value]="baseCoin.ID" to [value]="baseCoin.Abbr", the correct string is shown when I select an item, however, I need the (ngModelChange) event to return the baseCoin.ID to a method, instead of the baseCoin.Abbr.
<mat-form-field>
<input matInput placeholder="Base Coin" aria-label="Base Coin" [matAutocomplete]="basecoin" [formControl]="baseCoinCtrl" [(ngModel)]="newTrade.BaseCoin.Abbr" (ngModelChange)="populateMarketCoins( $event )">
<mat-autocomplete #basecoin="matAutocomplete">
<mat-option *ngFor="let baseCoin of filteredBaseCoins | async" [value]="baseCoin.Abbr">
{{baseCoin.Abbr | uppercase}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
Am I missing something?
Help is appreciated. Thanks.
Take a look at "Setting separate control and display values" from the docs. The autocomplete has an @Input() displayWith
which is a "Function that maps an option's control value to its display value in the trigger".
displayFn(baseCoin) {
return baseCoin ? baseCoin.Abbr : undefined;
}
<mat-autocomplete #basecoin="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let baseCoin of filteredBaseCoins | async" [value]="baseCoin">
{{baseCoin.Abbr | uppercase}}
</mat-option>
</mat-autocomplete>
I would also like to add that Autocomplete has an
@Output() optionSelected: EventEmitter<MatAutocompleteSelectedEvent>
property, which is an "Event that is emitted whenever an option from the list is selected". The Select also has a similar output. onSelectionChanged
however, is an "Event emitted when the option is selected or deselected."