I have multiple <mat-button-toggle> elements generated in my app and I want always only one selected. The problem that I now have is, how to get the component reference to the last selected toggle-button when another toggle button is clicked.
I really searched quite a while but couldn't understand how to do it.
component.html
<mat-button-toggle (click)="onKeywordSelect($event)" *ngFor="let keyword of keywords" [id]="keyword.id" [attr.id]="keyword.id" [value]="keyword.id" class="keyword">
<div class="text">{{ keyword.name }}</div>
</mat-button-toggle>
component.ts
// imports and @Component
export class NavbarComponent implements OnInit {
keywords = [new Keyword('name1'), new Keyword('name2')]; // sample data
$selectedKeyword: $ | any; // I've imported JQuery
onKeywordSelect(event: any) {
// This element depends on where you mouse was positioned when clicking
// Most often not the <mat-button-toggle> but some child element
const target = event.target;
// To get to the <mat-button-toggle> component that was clicked
const matButton = $(target).closest('mat-button-toggle');
if (this.$selectedKeyword !== undefined) {
// At the start there is no selected keyword
// TODO: Set the 'checked' property of the cur selected keyword to false
}
this.$selectedKeyword = $matButton;
}
}
I tried it with @ViewChild() but because the id of the selected keyword changes when the user selects one I don't know how to keep track of the selected component reference.
Edit
Forgot to mention: Yes I'm aware of mat-button-toggle-group but I don't want to use it because of some styling. Is there no other way to solve this?