我正在尝试以编程方式设置2个字段<input matInput>
和<mat-select>
之间的值。对于文本输入,一切正常,但是对于视图中的<mat-select>
,此字段就像null
的值一样。但是,如果我要调用console.log(productForm.controls['category'].value
,它将打印我以编程方式设置的正确值。我想念什么吗?
这里是代码:
表单配置:
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>
我正在尝试以编程方式设置2个字段的值abnd
通过将<mat-option>
的值从category
对象更改为其ID解决了此问题。
mat-select
中所有可用对象之间的角度mat-select
按参考比较
您可以使用对象来实现此目的的方法是像这样更改标记:
我认为在这里您应该使用FormGroup.setValue
。