Reputation: 2034
I have a toggle/Slide-toggle button in my app. Below is how it looks
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
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
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
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