<mat

编程入门 行业动态 更新时间:2024-10-22 17:30:11
本文介绍了<mat-select>的设置值以编程方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

更多推荐

[db:关键词]

本文发布于:2023-04-21 09:44:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1000464.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:amp   lt   mat

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!