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.
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;
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With