mat-slide-toggle Angular Material toggle programmatically
Asked Answered
F

2

11

I am trying to toggle the toggle() via code:

template

<mat-slide-toggle color="primary" (change)="updateFunc($event)"></mat-slide-toggle>

ts

updateFunc(e) {
  // do some checks to see if can be activated
  // if can't be activated, don't slide to on
  e.checked = false; // <--- does not work
  e.toggle(); // <-- does not work
}

Any ideas?

--EDIT--

To clarify, after the change event, the button is toggled to on. My function is run to do some tests. If the tests do not pass, I want to toggle the slider back to the off position. So, how do I toggle the button (on or off) in my code? This is simply a question of using the toggle() method in my code, or unchecking the switch in my code.

Fenrir answered 13/10, 2019 at 16:30 Comment(2)
mat-slide-toggle has an input property checked, initially you assign this to either true or false then on change event, you can toggle it.Antilogarithm
I am well aware, but I want to change it back programmatically after it has been changed, how do I do this?Fenrir
H
10

https://stackblitz.com/edit/angular-material-edh46h

<mat-slide-toggle #toggleElement class="example-margin" [checked]="checked" (change)="updateFunc($event)">
    Slide me!
</mat-slide-toggle>
  @ViewChild("toggleElement") ref: ElementRef;

  checked: boolean;

  ngOnInit() {
    this.checked = true;
  }

  updateFunc(e) {
    const someCondition = true;
    if (someCondition) {
      this.ref.checked = false;
    }
  }
Honey answered 13/10, 2019 at 19:30 Comment(1)
This worked. However, instead of using ViewChild, I simply passed the element into the function. Thanks!Fenrir
B
4

You can make use of template reference variable only.

template

<mat-slide-toggle color="primary" #slide (change)="updateFunc(slide)">
</mat-slide-toggle>

ts

updateFunc(e) {
 let var=false;
 if(!var)
 {
   e.checked = true; //either true or false 
 }
Belting answered 13/4, 2021 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.