angularangular-materialangular5angular-material2

mat-slide-toggle shouldn't change it's state when I click cancel in confirmation window


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


Solution

  • 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