无法为 angular 中的 md-select 设置默认值 2
Cannot set default value for md-select in angular 2
我无法在 angular 中为 md-select 设置值 2. 我正在从构造函数中填充 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 中正确访问此值。
但该值未加载到 select 字段中。 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>
如有任何帮助,我们将不胜感激。提前致谢!
您没有发布完整的代码,但没有它我会尽力帮助您。首先,如果上面有 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']);
});
我无法在 angular 中为 md-select 设置值 2. 我正在从构造函数中填充 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 中正确访问此值。 但该值未加载到 select 字段中。 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>
如有任何帮助,我们将不胜感激。提前致谢!
您没有发布完整的代码,但没有它我会尽力帮助您。首先,如果上面有 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']);
});