Displaying ngModel value for mat-select

ellier7 picture ellier7 · Jan 9, 2018 · Viewed 28.6k times · Source

I am using Angular Material Select to display holidays. When the user selects a holiday, I would like to display the date instead of the holiday name. For example, if the user selects "Christmas", I want the selected value to should show "December 25"

<mat-form-field>
  <mat-select [(ngModel)]="selectedHoliday" placeholder="Select A Holiday" (change)="eventSelection($event.value)">
    <mat-option *ngFor="let holiday of holidays" [value]="holiday">{{ holiday.name }}</mat-option>
  </mat-select>
</mat-form-field>

I set ngmodel to the correct date on select change:

selectedHoliday: string;

holidays = [
 { name: 'Christmas', date: 'Dec 25'} ,
 { name: 'New Years', date: 'Jan 1'}
]


eventSelection(event){
 this.selectedHoliday = event.date
}

When I set selectedHoliday to the date, nothing displays as the selected value. Here is a plunker: https://plnkr.co/edit/9lhHJhNyuWUxqYF6nMwK?p=preview

Answer

Sashel Niles Gruber picture Sashel Niles Gruber · Jan 10, 2018

The options value is set to the holiday object and [(ngModel)] is set to the date property of the selected event, in your case holiday.date.

So the select looks for the option with value holiday.date but your options have value holiday.

The select [(ngModel)] has to correlate to the value of its option.

[value]="holiday.date"

Updated Plunker fork