我正在使用帶有角材料芯片的多選復選框。我有帶有名稱和 id 的陣列物件,如果用戶選擇選項和 id 必須發送到后端,則應該顯示名稱。當我分配[value]="topping.id"時,它顯示選定的 id 而不是名稱。當用戶選擇選項并保留 id 時,如何在 UI 中顯示名稱formControl?我在這里添加了演示鏈接。
圖 1:當前結果
圖 2:預期結果

預期結果(圖 2):

- 專案清單
uj5u.com熱心網友回復:
問題在于以下代碼行:
<mat-option *ngFor="let topping of toppingList" [value]="topping.id">
您告訴 Angular 使用 id 作為表單控制元件值的值。一個解決方案是不只使用 id,而是將這些 id 映射到頂部物件本身。然后您的控制元件使用頂部物件而不是僅使用數字。這是您需要更改的代碼:
<mat-chip
*ngFor="let topping of idsToToppings(toppingsControl.value)"
[removable]="true"
(removed)="onToppingRemoved(topping.id)"
>
{{ topping.name }}
并在您的組件中添加以下方法:
idsToToppings(ids: number[]) : any[] {
return ids.map((id) => {
return this.toppingList.find((t) => t.id == id);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/479667.html
