<mat-select>的设置值以编程方式 [英] Set value of <mat-select> programmatically

查看:24
本文介绍了<mat-select>的设置值以编程方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式设置 2 个字段的值 abnd .对于文本输入,一切都按预期工作,但是对于视图上的 ,此字段就像它具有 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>

推荐答案

通过将 的值从 category 对象更改为它的身份证.

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

这篇关于&lt;mat-select&gt;的设置值以编程方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆