设定值 编程

问题描述 投票:10回答: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>

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

解决了这个问题,将<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);

9
投票

Angular无法选择您在类别字段中设置的项目,因为它通过引用来比较该对象与mat-select中的所有可用对象,因此您必须自己实现compare函数,并将其传递给[ 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


6
投票

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

<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;
}

0
投票

我想在这里你应该使用FormGroup.setValue

根据你的代码,

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

欲了解更多信息,请参阅documentation

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