Angular Material Button Toggle Group can be set to multiple and then from 0 to all buttons can be selected in the group.
Is there a way to force that at least one Button has to be selected and also set a maximum of selected buttons (if the limit is 2 and the user selects a third button, the first selected button should change to not selected).
Is it possible to achieve this with mat-button-toggle-group?
Add a comment
|
1 Answer
You must work with the property "value" of the group. In change method, pass the whole "group" using a reference variable.
e.g.
<mat-button-toggle-group #group="matButtonToggleGroup"
multiple=true (change)="change(group)">
<mat-button-toggle *ngFor="let value of [1,2,3,4,5]" [value]="value">
<mat-icon>format_align_left</mat-icon>
</mat-button-toggle>
</mat-button-toggle-group>
<div class="example-selected-value">Selected value: {{group.value}}</div>
max:number=2;
change(group:any)
{
//group.value is an array with the elements selected
if (group.value.length>this.max)
{
let newValue=group.value;
newValue.shift();
group.value=newValue;
}
}
See stackblitz