When I checked the slide toggle it should work as expected. But when I try to uncheck it there is a confirmation window asking if you are sure. When I click cancel in that confirmation window, still the toggle changes to unchecked, which shouldn't happen. It should stay in the same state.
Here is my Html and TS Code
// html
<mat-slide-toggle
(change)="change($event)" [checked]="isChecked()" >
To-pay
</mat-slide-toggle>
TS code:
// ts
change(e) {
if(this.checked) {
if(confirm("Are you sure")) {
console.log("toggle")
}
else {
e.stopPropagation();
console.log("toggle should not change if I click the cancel button")
}
}
}
when the confirmation window comes while trying to uncheck the toggle button and I click the cancel option there, nothing should happen to the toggle. stopPropagation() is also not working.
Edit1 :I tried doing return false in else statement. didn't worked. Even tried to change the e.checked = false. It just changed the event object value but didn't prevent the toggle from slidding
Unfortunately you cannot use stopPropagation
with mat-slide-toggle
, you will need to programmatically set the checked value back to true
on the event in your else condition.
else {
e.source.checked = true;
console.log("toggle should not change if I click the cancel button")
}
Stackblitz
https://stackblitz.com/edit/angular-79yf7m?embed=1&file=app/slide-toggle-overview-example.ts
I was using MatDialog
as the confirmation window and I noticed the following behavior:
when MatDialog
is opened, the mat-slide-toggle displays as false
/ unchecked
value, even if the user has not made a decision:
Demo: https://stackblitz.com/edit/angular-79yf7m-4gdxbu?file=app/slide-toggle-overview-example.ts
That's because the change
event fires after the mat-slide-toggle
value changes.
In order to fix this issue, we have to reset the value to its previous (true
) immediately after the change
event fires, then let the user decide, and if it confirms the action, we'll update the value accordingly.
The code would be:
change(e) {
if (this.checked) {
// at first, reset to the previous value
// so that the user could not see that the mat-slide-toggle has really changed
e.source.checked = true;
const dialogRef = this.dialog.open(ConfirmDialogComponent);
dialogRef.afterClosed().subscribe(response => {
if (response) {
this.checked = !this.checked;
}
})
} else {
this.checked = !this.checked;
}
}
Demo: https://stackblitz.com/edit/angular-79yf7m-yzwwc7?file=app%2Fslide-toggle-overview-example.ts
You can prevent the toggle mechanism by listening for click event and then event.preventDefault() / event.stopImmediatePropagation(). Then open your dialog and according to the user selection you toggle the toggle yourself or not: toggleReference.toggle().
No need to set it back to true.
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