以编程方式设置的值>>

问题描述 投票:17回答:4

我正在尝试以编程方式设置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 对于文本输入,一切正常,但对于在视图上,此...

angular angular2-forms angular-material2 angular5 angular-reactive-forms
4个回答
16
投票

通过将<mat-option>的值从category对象更改为其ID解决了此问题。


12
投票
该对象与mat-select中所有可用对象之间的

角度mat-select 按参考比较


6
投票

您可以使用对象来实现此目的的方法是像这样更改标记:


0
投票

我认为在这里您应该使用FormGroup.setValue

© www.soinside.com 2019 - 2024. All rights reserved.