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
We can use NgModel to get and set values in Select option for Angular Material Select as well as native Select. Suppose we have component property. selectedGame = "Football"; Use ngModel with <mat-select> to set and get value as following.
The compareWith just literally compares objects by some given values and the checkboxes get selected, if it returns true . In my code, I decided to go with the ng-Model binding but it works with formControl as well: <mat-form-field> <mat-select multiple[compareWith]="compareFn" name="users. [(ngModel)]="users">
Each <mat-option> has a value property that can be used to set the value that will be selected if the user chooses this option. The content of the <mat-option> is what will be shown to the user. Angular Material also supports use of the native <select> element inside of <mat-form-field> .
Create a form with fieldset in it and mat-select in it (form -> fieldset -> mat-select) Add [disabled] to fieldset inside form tag to be true on submit. Force disabled to become true.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With