I have a select multiple using the Angular Material mat-select
component. My options are displaying correctly in the dropdown but the selected values are not persisting to the UI. For example, on page load locationNameSelectedItems
returns -
[{
id: 60
itemName: "Main Location - 1100 Superior Road"
}]
<mat-form-field>
<mat-select [(ngModel)]="locationNameSelectedItems" formControlName="locationName" multiple>
<mat-option *ngFor="let location of locationNameDropdownList" [value]="location.id">{{location.itemName}}</mat-option>
</mat-select>
</mat-form-field>
How can I ensure that the correct selections are displayed?
I had similar situation, where I wanted to do two-way binding with mat-select and mat-option, I solved with below approach. this might not be an accurate solution but this could helpful to you.
In TypeScript file mention model object
category: CategoryModel = {
categoryId: 1,
// other fields(if any)
};
Then in HTML template use snippet code like given below,
<mat-select name="categoryId" [(ngModel)]="category.categoryId" required>
<mat-option *ngFor="let categ of categories" [value]="categ.categoryId">
{{ categ.categoryTitle }}
</mat-option>
</mat-select>