How do I set default value on md-select component from angular 2 material design?

血红的双手。 提交于 2019-12-04 00:00:47

you may try below,

Component HTML

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

  <p> Selected value: {{selectedValue}} </p>

Component script

@Component({
  selector: 'select-form-example',
  templateUrl: './select-form-example.html',
})
export class SelectFormExample {
  foods = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];


   // setting this is the key to initial select.
   selectedValue: string = this.foods[0].value;
}

The key here is setting selectedValue with the initial value.

Check this StackBlitz.

Hope this helps!!

To set default value to md-select you need to set default value to the variable that you are using in [(ngModel)]. In your case:

Component Html =>

<md-select  
            placeholder= "Warehouse" style="width: 100%"
            [(ngModel)]='selectedProductWarehouse.warehouse'
            name="Warehouse"
            required
            #Warehouse="ngModel">
  <md-option *ngFor="let warehouse of warehouses" [value]="warehouse">
            {{warehouse.description}}
 </md-option>
</md-select>

Component Script =>

@Component({
  selector: 'select-form-example',
  templateUrl: './select-form-example.html',
})

constructor() {
  this.selectedProductWarehouse.warehouse = "default value"
}

When you use Objects in md-option value, the object reference of the default value and the correponding option in the options list are not equal.

To fix this, you need to override the default value using the correponding option in the options list before setting the FormGroup.

Check this example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!