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?
MatButtonToggle
component doesn't implementControlValueAccessor
therefore you can't usengModel
on it.ngDefaultControl
was introduced for other purposes.MatButtonToggle
is supposed to be a part ofmat-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:Plunker Example
If you are trying to use
mat-button-toggle
to switch between enabling / disabling something, you will have to use a binding onmat-button-toggle-group
, and make sure that themat-button-toggle
's themselves have the boolean values oftrue
andfalse
, not the string values. That is to say:With Angular 6.1.3 and Angular Material 6.4.6 using Slide Toggle (i.e.,
<mat-slide-toggle>
)Template
Component
I'm using this solution, and it conveniently aligns with the Style Guide rule:
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
and change your boolean to
myFlagForButtonToggle :string;