问题
I have a Mat Select dropdown with the following values from an Object List.
export class Product {
productId: number;
productCode: string;
productDescription: string;
}
The Mat select List is meant to emit the Whole object as follows:
<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>
Also have compareWith function; sometimes code and description may slightly vary depending on different erp systems in company, however ID is always the same, so we compare upon that.
compareProductObjects(object1:any, object2:any) {
if (typeof object2 === 'object') {
return object1 && object2 && object1.productId === object2.productId;
}
The ProductList has all the real list data. When I patch the form, where I have product Class (with 2 being Furniture), however making Code and Description null to test.
as
productTest.productId = 2;
productTest.productCode = null;
productTest.productDescription = null;
this.customer.form.patchValue({ productData: productTest});
Running this will patch the form, and Successfully change the dropdown item! However, the value in output mat select from console form only shows as
{productData: {productId = 2}}
It does Not show any of Code and Description; however it successfully changed the mat select item, Without Code and Description.
How do I make it so, when patching the form with only an ID, it will change and Emit the real object in the list?
Note:
Have 30 other items in this form. Everything else patches perfectly, textboxes, checkboxes, trying to prevent writing special exception cases for dropdown, and want to write one fluent method for other users, if possible
this.customer.form.get('productData').setValue(this.ProductList.find(x=>x.id==2)
回答1:
The formGroup does not know anything about the object. It is just passing it around in the controls. Only time the control is checking if the value send to the control matches one of items in the list options for mat-select. I think this is only place you can modify it, if you do not want to make an edge case functions.
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
}
I do not think this is idea, but if the object does not have a lot of properties, it should not be that bad.
Personally I would use:
this.customer.form.get('productData').patchValue(this.ProductList.find(x=>x.id==2)
来源:https://stackoverflow.com/questions/60783901/angular-mat-select-comparewith-id-number-and-emit-whole-object