Search code examples
angularangular-materialangular-directive

Binding Mat-Button-Toggle v binding Mat-Slide-Toggle


How come this works fine. I.E isPrint shows as true or false on clicking the slide toggle

<div>
 <mat-slide-toggle [(ngModel)]="isPrint" #toggleSlide></mat-slide- 
 toggle>
isPrint: {{ isPrint }}
</div>

But this does not work and gives the error ERROR Error: No value accessor for form control with an unspecified name attribute

<div>
  <mat-button-toggle [(ngModel)]="isPrint" #toggleBtn>Toggle</mat-button-toggle>
  isPrint: {{ isPrint }}
</div>

What am I not doing correctly?


Solution

  • Check WORKING STACKBLITZ

    MatButtonToggle component doesn't implement ControlValueAccessor, therefore, you can't use [(ngModel)] on it.

    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, you have to do something like below:~

    <mat-button-toggle 
        [checked]="isPrint" 
        (change)="isPrint = $event.source.checked">
        Toggle
    </mat-button-toggle>