<mat-select>的设置值以编程方式
问题描述:
我正在尝试以编程方式设置 2 个字段的值 abnd
.对于文本输入,一切都按预期工作,但是对于视图上的
,此字段就像它具有 null
的值一样.但是如果我调用 console.log(productForm.controls['category'].value
它会打印我以编程方式设置的正确值.我错过了什么吗?
I'm trying to set value of 2 fields <input matInput>
abnd <mat-select>
programatically. For text input everything works as expected however for the <mat-select>
on the view this field is just like it would have value off null
. But if I would call console.log(productForm.controls['category'].value
it prints correct value that I set programmatically. Am I missing something?
代码如下:
表单配置:
productForm = new FormGroup({
name: new FormControl('', [
Validators.required
]),
category: new FormControl('', [
Validators.required
]),
});
设置值:
ngOnInit() {
this.productForm.controls['name'].setValue(this.product.name);
this.productForm.controls['category'].setValue(this.product.category);
}
}
html:
<mat-form-field>
<mat-select [formControlName]="'category'"
[errorStateMatcher]="errorStateMatcher">
<mat-option *ngFor="let category of categories" [value]="category">
{{category.name}}
</mat-option>
</mat-select>
</mat-form-field>
答
通过将
的值从 category
对象更改为它的身份证.
Solved this issue with changing the value of <mat-option>
from category
object to its id.
<mat-form-field>
<mat-select [formControlName]="'category'"
[errorStateMatcher]="errorStateMatcher">
<mat-option *ngFor="let category of categories" [value]="category.id">
{{category.name}}
</mat-option>
</mat-select>
</mat-form-field>
和设置值:
this.productForm.controls['category'].setValue(this.product.category.id);