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

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

问题描述:

我试图以编程方式设置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);