Take a look at this Plunker: https://plnkr.co/edit/yu95hUrKlUh4Ttc5SwYD?p=preview
When I'm using <mat-slide-toggle>
, I am able to modify the values in my component:
<mat-slide-toggle [(ngModel)]="myFlagForSlideToggle">Toggle me!</mat-slide-toggle>
myFlagForSlideToggle
is updated as expected.
But when I'm using <mat-button-toggle>
, the values are not updated. I had to add ngDefaultControl
to even make this example work, but I'm not sure how it matters.
<mat-button-toggle [(ngModel)]="myFlagForButtonToggle" ngDefaultControl>Toggle me!</mat-button-toggle>
What is the correct way to bind a button state to the component?
To create a toggle button or on/off button with angular material design and animations, the Angular <mat-button-toggle> directive is used. These buttons can be configured to behave like either radio buttons or checkboxes so that a single selection or multiple selections can be done on the buttons.
By default, mat-button-toggle-group acts like a radio-button group- only one item can be selected. In this mode, the value of the mat-button-toggle-group will reflect the value of the selected button and ngModel is supported. Adding the multiple attribute allows multiple items to be selected (checkbox behavior).
Mat-button-toggle buttons are configured to behave as radio buttons or checkboxes. They are part of <mat-button-toggle-group>. <mat-button-toggle> are on/off toggles with the appearance of a button. These toggles can be configured to behave as either radio-buttons or checkboxes.
The <mat-button-toggle>, an Angular Directive, is used to create a toggle or on/off button with material styling and animations. mat-button-toggle buttons can be configured to behave as radio buttons or checkboxes.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With