Uncheck active Angular Material toggle buttons on click
A simple generic solution that doesn't require resorting to events on each button or click events at all, and doesn't require ViewChildren or hard-coding value checks, is to use the button toggle in multiple mode and manage selections through the group change event. The change event gives you all you need so there is no need to access child components directly:
<mat-button-toggle-group multiple (change)="toggleChange($event)">
<mat-button-toggle value="no">No</mat-button-toggle>
<mat-button-toggle value="yes">Yes</mat-button-toggle>
</mat-button-toggle-group>
toggleChange(event) {
let toggle = event.source;
if (toggle) {
let group = toggle.buttonToggleGroup;
if (event.value.some(item => item == toggle.value)) {
group.value = [toggle.value];
}
}
}
Here it is on Stackblitz.
Here is another solution. Note that the change
event occurs before the click
event.
Component
toggleChanged: boolean;
onChange() {
this.toggleChanged = true;
}
onClick(group: MatButtonToggleGroup) {
if (!this.toggleChanged) group.value = null;
this.toggleChanged = false;
}
Template
<mat-button-toggle-group [(value)]="myValue" #group="matButtonToggleGroup"
(change)="onChange()" (click)="onClick(group)">
<mat-button-toggle *ngFor="let item of items" [value]="item.value">
{{ item.name }}
</mat-button-toggle>
</mat-button-toggle-group>