以编程方式设置<mat-select>的值

时间:2018-02-14 22:24:33

标签: angular angular2-forms angular-material2 angular5 angular-reactive-forms

我正在尝试以编程方式设置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>

4 个答案:

答案 0 :(得分:13)

通过将<mat-option>对象的category值更改为其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);

答案 1 :(得分:5)

使用对象实现此目的的方法是更改​​标记,如下所示:

<mat-select [formControlName]="'category'"
        [errorStateMatcher]="errorStateMatcher" [compareWith]="compareFn">
<mat-option *ngFor="let category of categories" [value]="category">
    {{category.name}}
</mat-option>
</mat-select>

然后在组件

compareFn(x: Category, y: Category): boolean {
return x && y ? x.id === y.id : x === y;
}

答案 2 :(得分:4)

Angular无法选择您在category字段中设置的项目,因为它通过引用比较该对象与mat-select中所有可用对象之间的比较,因此您必须自己实现比较功能并将其传递在[compareWith]属性中,如下所示:

<mat-form-field>
<mat-select [formControlName]="category" [compareWith]="compareCategoryObjects">
    <mat-option *ngFor="let category of categories" [value]="category">
        {{category.name}}
    </mat-option>
</mat-select>

在组件类中:

compareCategoryObjects(object1: any, object2: any) {
        return object1 && object2 && object1.id == object2.id;
    }

现在它将选择项目-如果您为该字段设置了多个选择,则将选择项目。

参考:
https://github.com/angular/material2/issues/10214

工作示例:
https://stackblitz.com/edit/angular-material2-issue-t8rp7j

答案 3 :(得分:0)

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

根据您的代码,

this.productForm.setValue({
name: this.product.name,
category: this.product.category
});

有关更多信息,请参阅documentation

相关问题