Jonathan
Jonathan

Reputation: 4689

mat-slide-toggle Angular Material toggle programmatically

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.

Upvotes: 11

Views: 16535

Answers (2)

k_learner
k_learner

Reputation: 137

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 
 }

Upvotes: 4

Rohith Balaji
Rohith Balaji

Reputation: 860

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;
    }
  }

Upvotes: 10

Related Questions