How to mat-button-toggle by default selected in angular
Solution 1:
I fixed it. Simply add the value
attribute to the mat-button-toggle-group
tag.
<mat-button-toggle-group #group="matButtonToggleGroup" value="All">
<mat-button-toggle value="Heritage">
<span>Heritage</span>
</mat-button-toggle>
<mat-button-toggle value="Nature">
<span>Nature</span>
</mat-button-toggle>
<mat-button-toggle value="People">
<span>People</span>
</mat-button-toggle>
<mat-button-toggle value="All">
<span>All</span>
</mat-button-toggle>
Solution 2:
Hope this will help someone.
public selectedVal: string;
constructor() { }
ngOnInit(){
this.selectedVal ='option1';
}
public onValChange(val: string) {
this.selectedVal = val;
}
<mat-button-toggle-group #group="matButtonToggleGroup" [value]="selectedVal" (change)="onValChange(group.value)" >
<mat-button-toggle value="option1">
Option 1
</mat-button-toggle>
<mat-button-toggle value="option2">
Option 2
</mat-button-toggle>
</mat-button-toggle-group>
Solution 3:
@Uliana Pavelko's answer is awesome. But what would be for multiple selected button group?
Bellow is the example. Don't forget to pass values as string in
public selectedVal: string;
constructor() { }
ngOnInit(){
this.selectedVal =['2','6'];
}
public onValChange(val: string) {
this.selectedVal = val;
}
<mat-button-toggle-group #group="matButtonToggleGroup" [value]="selectedVal" (change)="onValChange(group.value)" >
<mat-button-toggle value="option1">
Option 1
</mat-button-toggle>
<mat-button-toggle value="option2">
Option 2
</mat-button-toggle>
</mat-button-toggle-group>