在我的案例中,角度角色是从 API 接收 JSON-实体并将其值分配给FormGroup
。
一切正常(FormGroup
包含所有期望值),但是mat-select
不能从视觉上预先选择给定值。
onInit()
方法中包含了前面描述的所有功能。
product-group-update.component.ts: 完整代码:https://pastebin.com/hXLqBAcF
export class ProductGroupUpdateComponent implements OnInit {
NO_PRODUCT: string = 'No product';
editProductGroupForm: FormGroup;
id: number;
isFormSubmitted = false;
availableProducts: Product[];
toSelect: Product[];
constructor(
private formBuilder: FormBuilder,
private productGroupService: ProductGroupService,
private productService: ProductService,
private router: Router,
private activatedRoute: ActivatedRoute,
private location: Location,
) {
}
ngOnInit(): void {
this.editProductGroupForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.maxLength(100)]],
description: ['', [Validators.required, Validators.maxLength(100)]],
products: ['', []],
});
this.activatedRoute.paramMap.subscribe(params => {
this.id = +params.get('id');
this.productGroupService.getProductGroupById(this.id).subscribe(
receivedProductGroup => {
this.toSelect = receivedProductGroup.products;
this.editProductGroupForm.setValue({
name: receivedProductGroup.name,
description: receivedProductGroup.description,
products: receivedProductGroup.products,
});
}
);
});
console.log(this.editProductGroupForm)
this.productService.getAllProducts(new Page<Product>()).subscribe(response => {
this.availableProducts = response.content;
});
}
...
}
product-group-update-component.html 完整代码:https://pastebin.com/9GqyU2r2
<div class="col-md-12">
<div class="card card-container">
<form (ngSubmit)="submitForm()" [formGroup]="editProductGroupForm" class="new-obj-form" id="register-form">
...
<mat-form-field appearance="fill" class="example-full-width">
<mat-label>Products</mat-label>
<mat-select formControlName="products" multiple [(value)]="toSelect">
<mat-option [value]="NO_PRODUCT">{{NO_PRODUCT}}</mat-option>
<mat-option *ngFor="let product of availableProducts" [value]="product">
{{product.name}}
<i><small>(ID: {{product.id}})</small></i>
</mat-option>
</mat-select>
</mat-form-field>
...
</form>
</div>
</div>
您将看到:editProductGroupForm
包含所有值:
还有toSelect
元素(mat-select应该从中采用预选的值)
其他代码:
export interface Product {
id: number;
name: string;
description: string;
price: number;
groupId: number;
sold: boolean;
}
import {Product} from "./product";
export interface ProductGroup {
id: number;
name: string;
description: string;
products: Product[];
}
答案 0 :(得分:1)
请记住,availableProducts
和toSelect
中的产品是不同的对象。因此,即使它们具有相同的属性,但它们仍然是不同的实例,这意味着对象的比较将返回false-这就是为什么未选择它们的原因。
您可以使用两种不同的方法来修复它:
mat-select
支持compareWith
功能-因此,您可以覆盖默认比较并按ID比较它们。有关其工作原理,请参见官方的角度文档here。 material docs中也提供了一个示例。toSelect
是availableProducts
表中对象的实际实例。