How to bind to model with Angular Material <mat-button-toggle>?
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>
If you are trying to use mat-button-toggle
to switch between enabling / disabling something, you will have to use a binding on mat-button-toggle-group
, and make sure that the mat-button-toggle
's themselves have the boolean values of true
and false
, not the string values. That is to say:
<mat-button-toggle-group [(ngModel)]="isEnabled">
<mat-button-toggle [value]="true"> Enable </mat-button-toggle>
<mat-button-toggle [value]="false"> Disable </mat-button-toggle>
</mat-button-toggle-group>
MatButtonToggle
component doesn't implement ControlValueAccessor
therefore you can't use ngModel
on it. ngDefaultControl
was introduced for other purposes.
MatButtonToggle
is supposed to be a part of mat-button-toggle-group
. But if you want to use it as a standalone component and bind model to it here is some example of how you can do it:
<mat-button-toggle
[checked]="myFlagForButtonToggle"
(change)="myFlagForButtonToggle = $event.source.checked">
Toggle me!
</mat-button-toggle>
Plunker Example
mat-button-toggle
dont have a boolean value and [(ngModel)]
won't work. See doc.
These toggles can be configured to behave as either radio-buttons or checkboxes.
a use case may be like this
<mat-button-toggle-group [(ngModel)]="myFlagForButtonToggle">
<mat-button-toggle value="button1" ngDefaultControl>Toggle me!</mat-button-toggle>
<mat-button-toggle value="button2" ngDefaultControl>Toggle me!</mat-button-toggle>
<mat-button-toggle value="button3" ngDefaultControl>Toggle me!</mat-button-toggle>
</mat-button-toggle-group>
and change your boolean to myFlagForButtonToggle :string;