zacko
zacko

Reputation: 399

Angular material slide toggle binding on checked not working

It seems to be so easy, but I just cannot get the checked binding of the slide toggle to work.

(I'm using angular 9.1 and material 9.2.)

Here's the html:

<mat-slide-toggle [checked]="isSlideChecked" (change)="toggleChanges($event)">isSlideChecked: {{isSlideChecked}}</mat-slide-toggle>

<p *ngFor="let e of toggleEvents">{{e}}</p>

Here's the TS:

import { Component, OnInit } from '@angular/core';
import { MatSlideToggleChange } from '@angular/material/slide-toggle';

@Component({
  selector: 'app-test-component',
  templateUrl: './test-component.component.html',
  styleUrls: ['./test-component.component.scss']
})
export class TestComponentComponent implements OnInit {

  public isSlideChecked: boolean = false;
  public toggleEvents: string[] = [];

  constructor() { }

  ngOnInit(): void {
  }

  toggleChanges($event: MatSlideToggleChange) {
    this.toggleEvents.push("Toggle Event: " + $event.checked)
  }
}

The change event is working fine, $event.checked is always set correctly. But the checked binding just won't work, it's always staying false.

Before I give up and use an odinary checkbox, I hoped someone here could help me. Any suggestions?

Upvotes: 6

Views: 18321

Answers (3)

Hossein
Hossein

Reputation: 240

anohter way using both[(ngModel)] and event change. get value by event and set value by [(ngModel)]:

component.html:

<mat-slide-toggle 
                 formControlName="myName" 
                 (change)="slideToggleChange($event)"
                 [(ngModel)]="checked">
</mat-slide-toggle>

component.ts

slideToggleChange(event: MatSlideToggleChange) {
    this.checked = event.source.checked;   
  }

Upvotes: 2

Ani
Ani

Reputation: 391

The property checked of material slide toggle is only for input binding. Because of that any changes to the toggle by clicking will not be output in [checked]. You will have to use the (change) event to assign the values from the event.checked.

toggleChanges($event: MatSlideToggleChange) { this.isSlideChecked = $event.checked; }

You can refer the API documentation for more details, https://material.angular.io/components/slide-toggle/api

Upvotes: 8

here's a link to the working stackblitz.

I'm not sure why, but when I removed the public from isSlideChecked, the binding started to work. I also removed the public from the toggleEvents array as well. Hope this helps.

Upvotes: 0

Related Questions