Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 284
Jonathan Avatar asked Mar 31 '26 00:03

Jonathan


2 Answers

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;
    }
  }
like image 104
Rohith Balaji Avatar answered Apr 02 '26 12:04

Rohith Balaji


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 
 }
like image 20
k_learner Avatar answered Apr 02 '26 14:04

k_learner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!