无法在角度2中为md-select设置默认值

时间:2017-03-02 13:47:17

标签: angular angular-material angular-ngmodel md-select

我无法在角度2中为md-select设置值。我在构造函数中填充选择列表,如:

 constructor() {
      this.testService.getTypes()
        .subscribe(result => {
            if (result.code === 200) { 
                this.types = result.data;                        
            }
        }, error => {
            this.router.navigate(['signin']);
        });
}

工作正常,数据在md-select上正确填充。然后我在运行一些查询后设置ngOnInit()的值,并将值设置为:

this.selectedValue = 'value';

我可以使用{{selectedValue}}正确地在html中访问此值。 但该值未加载到选择字段。 md-select代码是:

<md-select placeholder="Type" [(ngModel)]="selectedValue"  [formControl]="form.controls['typeName']"  [required]="isRequired"  style="width: 100%">
      <md-option *ngFor="let type of types" [value]="type.typeId" [disabled]="type.disabled">
            {{ type.typeName }}
     </md-option>

任何帮助将不胜感激。提前谢谢!

1 个答案:

答案 0 :(得分:1)

你没有发布完整的代码,但我会尽力帮助你。首先,如果你有一个formControl,你不需要ngModel。它基本上做同样的事情 - 双向数据绑定。

this.testService.getTypes()
    .subscribe(result => {
        if (result.code === 200) { 
            this.types = result.data; 
            this.form.controls['typeName'].setValue(this.types[0].typeId); //add this line                     
        }
    }, error => {
        this.router.navigate(['signin']);
    });
相关问题