如何在 angular 2 material design 的 md-select 组件上设置默认值? [英] How do I set default value on md-select component from angular 2 material design?

查看:29
本文介绍了如何在 angular 2 material design 的 md-select 组件上设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下选择组件,该组件从来自 rest api 的数据填充.如何在 md-select 上设置默认选定值?

I have the following select component that gets populated from a data coming from a rest api. How Can I set default selected value on md-select?

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

推荐答案

你可以试试下面的,

组件 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({
  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;
}

这里的关键是用初始值设置selectedValue.

The key here is setting selectedValue with the initial value.

检查这个 StackBlitz.

希望这有帮助!!

这篇关于如何在 angular 2 material design 的 md-select 组件上设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆