【问题标题】:Cannot set default value for md-select in angular 2无法在角度 2 中设置 md-select 的默认值
【发布时间】:2017-07-22 06:47:57
【问题描述】:

我无法在角度 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-选择代码是:

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

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

【问题讨论】:

  • 如果你有一个formControl,你就不需要ngModel。它将直接从 formControl 中获取值。

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


【解决方案1】:

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

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']);
    });

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 2015-02-21
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多