Search code examples
angularangular-material

Angular Material component mat-select ngModel not persisting selected choice


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?


Solution

  • 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>
    
    • categories are fetched from backend in my case, you can hard code in TS file
    • Do not forget to give name attribute to mat-select tag where name should be same as the field you want to update in object. In my case it is categoryId
    • And in mat-option tag use [value] as field-name of your object you want to update in object/model.