Reputation: 31
In my Angular 5 application, I have an input box that, when enter is pressed, calls an API that returns an array. This array is then used in an mat-select to populate the mat-options. The first item is automatically selected, but the display value never updates.
In other words, when a mat-select is populated with dynamic data, an assignment to its ngModel is not reflected in its display value.
component.html
:
<mat-form-field>
<input matInput placeholder="Order ID" [(ngModel)]="orderID (keydown)="handleKeyDown($event)">
</mat-form-field>
<mat-form-field>
<mat-select placeholder="Product ID" (change)="showProductDetails(productID)" [(ngModel)]="productID" >
<mat-option *ngFor="let product of products" [value]="product.id"> {{ product.name }} </mat-option>
</mat-select>
</mat-form-field>
component.ts
:
orderID = '';
products = [];
handleKeyDown(event: any) {
if (event.keyCode === 13) { this.getProductIDs(); }
}
getProductIDs(){
... /~ Call API and populate "products" ~~/
// Update the mat-select's ngModel - value is updated but display is not
productID = products[0].id;
}
showProductDetails(productID){ /~~ Do some stuff }
Upvotes: 3
Views: 19919
Reputation: 16384
An example from Angular Material docs:
So you should use [(value)]
instead of regular [(ngModel)]
, like this:
<mat-form-field>
<mat-select placeholder="Product ID" (change)="showProductDetails(productID)" [(value)]="productID" >
<mat-option *ngFor="let product of products" [value]="product.id"> {{ product.name }} </mat-option>
</mat-select>
</mat-form-field>
Upvotes: 4