I wanna know if it's possible have a "mix" of mat-select
and mat-chip-list
. In the chip-list
, I want to show the selected options from mat-select
.
If it is, how can I do it?
Is it possible to use mat-select and mat-chips together? Bookmark this question. Show activity on this post. I wanna know if it's possible have a "mix" of mat-select and mat-chip-list. In the chip-list, I want to show the selected options from mat-select. If it is, how can I do it? Show activity on this post. Yes, it is possible.
You need to use <mat-select-trigger> within <mat-select>. Inside <mat-select-trigger> place <mat-chip-list>.
In Angular Material, the select component is created by adding the <mat-select/> or native <select/> components. <mat-select/> or <select/> component can be used in a form-field created by adding <mat-form-field/> component. Let’s quickly start exploring the Material Mat Select component…
To create and display chips selection, we will use the Angular Material Ui library in the angular app. Chips allow users to enter information, make selections, filter content, or invoke actions. Chips are not that difficult to develop, primarily if you use angular material in Angular app development.
Yes, it is possible. You need to use <mat-select-trigger>
within <mat-select>
. Inside <mat-select-trigger>
place <mat-chip-list>
.
In your HTML template you need something like:
<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">{{topping}}</mat-option>
</mat-select>
</mat-form-field>
<br/> <!-- only for debug -->
{{ toppingsControl.value | json }}
And in your ts
:
@Component({
selector: 'select-multiple-example',
templateUrl: 'select-multiple-example.html',
styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample {
toppingsControl = new FormControl([]);
toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
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);
}
}
}
Here is a complete example with Angular Material 9, but it works the same in version 6.
I hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With