问题
How can I set default selected last button in toggle group.
This is my code.
<mat-button-toggle-group #group="matButtonToggleGroup">
<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>
</mat-button-toggle-group>
回答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>
回答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>
回答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>
回答4:
For people using a FormBuilder, I propose to fill the default value from .ts
file
example:
formControlName : ['All', Validators.required]
来源:https://stackoverflow.com/questions/47637469/how-to-mat-button-toggle-by-default-selected-in-angular