Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 365
ellier7 Avatar asked Jan 09 '18 14:01

ellier7


People also ask

Can we use ngModel with Mat-select?

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.

What is compareWith in mat-select?

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">

What is Mat value option?

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> .

How do you readonly mat-select?

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.


1 Answers

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

like image 170
Sashel Niles Gruber Avatar answered Oct 01 '22 04:10

Sashel Niles Gruber