Shruti Nair
Shruti Nair

Reputation: 2034

stop checkbox from changing state till function executes

I have a toggle/Slide-toggle button in my app. Below is how it looks

enter image description here

When the user clicks on the toggle I don't want the toggle to change immediately rather it should wait for the change function to execute and then change its appearance on the view.

Currently, the toggle changes first and doesn't wait for the function to execute. I don't want the toggle to change state if the function fails

I tried event.preventDefault();

But somehow I'm not able to achieve the desired result.

<div>
   <label class="i-switch i-switch-lg pull-right">
      <input type="checkbox" name="myToggle" [(ngModel)]="toggleStatus" (click)="authenticate($event)" />
         <i></i>
   </label>
 </div>

[Css not included]

Upvotes: 0

Views: 45

Answers (3)

Shruti Nair
Shruti Nair

Reputation: 2034

Got it working with a combination of two of the answers

changed to

[ngModel]="toggleStatus" and used

evt.stopPropagation()

<input type="checkbox" name="myToggle" [ngModel]="toggleStatus" (click)="authenticate($event)" />

and in authenticate function used

authenticate(e: any) {
    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
    e.stopPropagation();
}

Upvotes: 0

Arielle Nguyen
Arielle Nguyen

Reputation: 3172

You would need a fetch/promise or observable to execute the change in look once your authentication (assuming asynchronous) completes. Besides preventDefault, you might also need to use stopPropagation. Can you please post a link to debug? Try CodeSandbox.

Try this

hello(evt) {
    evt.preventDefault();
    evt.stopPropagation();

    fetch("https://jsonplaceholder.typicode.com/todos/1").then(
      this.handleAuthentication
    );
}
handleAuthentication() {
    alert("you can change button now");
  }
}

Upvotes: 0

Sebastian Oleński
Sebastian Oleński

Reputation: 538

Your .ts should look like this :

  toggleStatus: boolean;

  authenticate($event){
    $event.preventDefault()
    // do stuff

    //this.toggleStatus = true;

  }

and in html change the binding from two-way to one-way

so

[(ngModel)]="toggleStatus"

to

[ngModel]="toggleStatus"

here's a stackblitz with your example

https://angular-xfziiu.stackblitz.io

Upvotes: 1

Related Questions