How to mat-button-toggle by default selected in angular

我的未来我决定 提交于 2021-01-21 06:12:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!