ellier7
ellier7

Reputation: 427

Displaying ngModel value for mat-select

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

Upvotes: 12

Views: 62757

Answers (1)

Sashel Niles Gruber
Sashel Niles Gruber

Reputation: 1221

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

Upvotes: 18

Related Questions