ngx-ui-switch
ngx-ui-switch copied to clipboard
How to use beforeChange in real live
Hello
I have some issue with the beforeChange observable. It works perfect with the sample, but I have strange behavior in a "real life".
Here is very ugly sample for the demo, it emulates htppClient behavior by using of(). The idea behind is to make a call to the server and depends on the result allow or disallow change: https://stackblitz.com/edit/ngx-ui-switch-fuojps?file=src%2Fapp%2Fdemo%2Fdemo.component.html
Take a look on the console: the onBeforeChange called many times even for not related items:
onBeforeChange: Item 1, value: false onBeforeChange: Item 2, value: false onBeforeChange: Item 1, value: false onBeforeChange: Item 2, value: false onBeforeChange: Item 1, value: true onBeforeChange: Item 2, value: false onBeforeChange: Item 1, value: true onBeforeChange: Item 2, value: false
Is this a bug or expected?
That is odd. I poked around at the demo and it happens without the ngFor
as well.
I think it's a bug.
There's definitely a race condition or problem with disabling the switch during the beforeChange
.
beforeChange
works on the premise of you provide an Observable. That Observable will send a truthy value back if the switch state is to be updated.
Do you have specifics on your use case? Are you sending multiple switch values to a backend at the same time and waiting for them?
Hello
I need help here as I am not able to handle the beforeChange event. I want to show confirm modal when switch is toggle and I have used NgbModal for modal but function is not waiting to get finished as Promise is not working inside observable.
HTML
<ui-switch
[checked]="value === 1 ? true : false"
size="small"
(click)="selectedUser = row.id"
[beforeChange]="checkBefore"
placement="bottom"
[ngbTooltip]="value === 1 ? 'Enabled' : 'Disabled'"
></ui-switch>
Code
checkBefore: Observable<boolean> = new Observable((observer) => {
this.openModal().subscribe((res) => {
observer.next(true);
console.log(res));
});
return () => clearTimeout(timeout);
});
openModal(): Observable<any> {
const promise = new Promise(async (resolve, reject) => {
const modalRef = this.modalService.open(NgbdConfirmModal, {
size: 'sm',
animation: true,
centered: true,
});
modalRef.dismiss((res: any) => {
console.log(res);
resolve(res);
});
});
return of(promise);
}
But nothing working for me. And If I changed code to below method then modal is visible but not waiting for response.
checkBefore: Observable
this.modalService.open(NgbdConfirmModal, {
animation: true,
centered: true,
});
return () => clearTimeout(timeout);
});