AnotherMike
AnotherMike

Reputation: 2913

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

Upvotes: 0

Views: 762

Answers (1)

yurzui
yurzui

Reputation: 214047

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

Upvotes: 1

Related Questions