gpt4 book ai didi

Angular Mat 选择 CompareWith ID 编号,并发出整个对象

转载 作者:行者123 更新时间:2023-12-05 07:11:25 24 4
gpt4 key购买 nike

我有一个 Mat Select 下拉菜单,其中包含对象列表中的以下值。

export class Product {
productId: number;
productCode: string;
productDescription: string;
}

Mat select List 旨在发出 Whole 对象,如下所示:

<mat-form-field>
<mat-select formControlName="productData" [compareWith]="compareProductObjects"
<mat-option>Select</mat-option>
<mat-option *ngFor="let productItem of ProductList" [value]="productItem">
{{productItem.productDescription}}
</mat-option>
<mat-select>
</mat-form-field>

还有compareWith函数;有时代码和描述会因公司不同的erp系统而略有不同,但ID总是相同的,所以我们比较。

compareProductObjects(object1:any, object2:any) {
if (typeof object2 === 'object') {
return object1 && object2 && object1.productId === object2.productId;
}

ProductList 拥有所有真实的列表数据。当我修补表格时,我有产品类别(2 是家具),但是使代码和描述为空以进行测试。

作为

productTest.productId = 2;
productTest.productCode = null;
productTest.productDescription = null;

this.customer.form.patchValue({ productData: productTest});

运行这个将修补表单,并成功更改下拉项!但是,从控制台表单中选择的输出垫中的值仅显示为

{productData: {productId = 2}} 

它不显示任何代码和描述;但是它成功地更改了垫选择项,没有代码和描述。

我如何做到这一点,当只用一个 ID 修补表单时,它会改变并发出列表中的真实对象?

注意:

此表单中还有 30 个其他项目。其他一切都完美地修补,文本框,复选框,试图防止为下拉菜单编写特殊的异常情况,并希望为其他用户编写一种流畅的方法,如果可能的话

this.customer.form.get('productData').setValue(this.ProductList.find(x=>x.id==2)

最佳答案

formGroup 对对象一无所知。它只是在控件中传递它。只有当控件检查发送到控件的值是否与 mat-select 的列表选项中的一项匹配时。如果您不想制作边缘案例功能,我认为这是您可以修改它的唯一地方。

compareProductObjects(object1:any, object2:any) {
if (typeof object2 === 'object') {
const isValue = object1 && object2 && object1.productId === object2.productId;
if(isValue){
Object.assign(object2, object1)
}
return isValue;
}
return false
}

我不认为这是想法,但如果对象没有很多属性,应该不会那么糟糕。

我个人会使用:

this.customer.form.get('productData').patchValue(this.ProductList.find(x=>x.id==2)

关于Angular Mat 选择 CompareWith ID 编号,并发出整个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60783901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com