JordanBarber
JordanBarber

Reputation: 2101

Alter Value of Material Slide Toggle based on user response to javascript 'confirm'

I am implementing an Angular Material Slide Toggle. If the user is switching the toggle from true to false, I would like to show a confirmation making sure they want to do this. If they say cancel, I would like to keep the slide toggle set to true. What am I doing wrong?

Here's the html of the component:

<md-slide-toggle checked="checked" (change)="changeEvent($event)">Slide Toggle</md-slide-toggle>

And the component's typescript:

changeEvent(ev) {
    if (ev.checked === false) {
      var x = confirm("Are you sure?")
      if (!x) {
        return ev.checked === false; 
      }
    }
  }

And here's a plunker demonstrating what I have so far...http://plnkr.co/edit/WP55vlFQBljgKM0jkf2R?p=preview

How can I achieve this?

Upvotes: 2

Views: 940

Answers (1)

Vega
Vega

Reputation: 28738

Fist, set a model for the slider and change the name ('checked' seems causing an issue). Also use [] for the checked attribute. Then set that value to true or false when canceling or affirming in the dialog box. Otherwise ev.checked value is getting 'lost', it doesn't do anything:

HTML:

<md-slide-toggle [checked]="myValue" (change)="changeEvent($event)">Slide Toggle</md-slide-toggle>

TypeScript:

... 
if (ev.checked === false) {
      var x = confirm("Are you sure?")
      if (!x) {
        this.myValue = true; 
      }
}

Plunker

Upvotes: 1

Related Questions