设置为< mat-select& gt;的值.以编程方式 [英] Set value of &lt;mat-select&gt; programmatically
问题描述
我试图以编程方式设置2个字段的值< input matInput>
和< mat-select>
.对于文本输入,一切正常,但是对于视图中的< mat-select>
而言,此字段就像 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>
推荐答案
通过将< mat-option>
的值从 category
对象更改为其对象来解决此问题ID.
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);
这篇关于设置为< mat-select& gt;的值.以编程方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!