简体   繁体   中英

Set default value on md-select When Value is an Object Angular4 Angular-Material

I'm trying to pass an object, rather than a string, out of an md-select change event. This works fine, however, I am unable to preselect a value on load:

<md-select 
  [(ngModel)]="selectedValue" 
  name="food"
  (change)="onSelectionChange($event)"
>
  <md-option *ngFor="let food of foods" [value]="food">
    {{food.viewValue}}
  </md-option>
</md-select>

This doesn't work:

selectedValue: {value: 'steak-0', viewValue: 'Steak'};
[(ngModel)]="selectedValue" 

Nor does this:

selectedValue:'steak-0';
[(ngModel)]="selectedValue.value" 

Is there a way to preselect a value on load, when value is an object? Seems like a common use case.

https://plnkr.co/edit/IkAnPj4ABsWOM4mpqqK4?p=preview

If you deal with object value you should select the same object reference. So you can do it as follows:

foods = [
  {value: 'steak-0', viewValue: 'Steak'},
  {value: 'pizza-1', viewValue: 'Pizza'},
  {value: 'tacos-2', viewValue: 'Tacos'}
];

selectedValue = this.foods[0];

Fixed Plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM