I'm using multi select checkbox with angular material chip. I have array objects with name and id, name is supposed to be displayed if user select options and id must be sent to backend. When I assign [value]="topping.id"
, its showing selected id instead of name. How I can show name in UI when user select option and keep id in formControl
? I have added demo link here.
Image 1: Current result
Image 2: Expected result
- List item
CodePudding user response:
The problem lies with the following line of code:
<mat-option *ngFor="let topping of toppingList" [value]="topping.id">
You are telling angular to use the id as value for the form control values. A solution would be to instead of using only the id, map these ids to topping objects themselves. Then your control is using topping objects instead of only a number. Here is the code you need to change:
<mat-chip
*ngFor="let topping of idsToToppings(toppingsControl.value)"
[removable]="true"
(removed)="onToppingRemoved(topping.id)"
>
{{ topping.name }}
and add the following method in your component:
idsToToppings(ids: number[]) : any[] {
return ids.map((id) => {
return this.toppingList.find((t) => t.id == id);
});
}