'How to show selected name in angular material multi select checkbox and chips component
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
app.component.html
<mat-form-field>
<mat-label>Toppings</mat-label>
<mat-select [formControl]="toppingsControl" multiple>
<mat-select-trigger>
<mat-chip-list>
<mat-chip
*ngFor="let topping of toppingsControl.value"
[removable]="true"
(removed)="onToppingRemoved(topping)">
{{ topping }}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
</mat-chip-list>
</mat-select-trigger>
<mat-option *ngFor="let topping of toppingList" [value]="topping.id">
{{topping.name}}
</mat-option>
</mat-select>
app.component.ts
toppingsControl = new FormControl([]);
toppingList: any[] = [
{ id: 1, name: 'Extra cheese' },
{ id: 2, name: 'Mushroom' },
{ id: 3, name: 'Onion' },
{ id: 4, name: 'Sausage' }
];
onToppingRemoved(topping: string) {
const toppings = this.toppingsControl.value as string[];
this.removeFirst(toppings, topping);
this.toppingsControl.setValue(toppings); // To trigger change detection
}
private removeFirst<T>(array: T[], toRemove: T): void {
const index = array.indexOf(toRemove);
if (index !== -1) {
array.splice(index, 1);
}
}
- List item
Solution 1:[1]
Abstract base classes prevent you from instantiating an object unless you implement the abstract methods. This raises the error immediately and alerts you to the fact that you need to implement the method. This is especially helpful if you instantiate the class but don't call the method until after a lengthy execution process: you won't raise NotImplementedError until you call the method.
import abc
class AbstractClass(abc.ABC):
@abc.abstractmethod
def test(self):
pass
class NotAbstractClass:
def test(self):
raise NotImplementedError()
class AbstractInheritor(AbstractClass):
pass
class NotAbstractInheritor(NotAbstractClass):
pass
x = AbstractInheritor() # raises error immediately
y = NotAbstractInheritor() # no error despite not implementing test
In fact, the line where I create x is caught by my type checker, so I do not even need to run the code to know there is a problem. Meanwhile, y is perfectly fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |


