In Angular app(ver 11) when back button is pressed or location.back() is called if ngbModal is active I want it to be closed. After research that I made I came up with something like this:
modalService.activeInstances.subscribe((result: any) => {
if (result.length > 0) {
history.pushState(null, null, window.location.href);
}
})
@HostListener('window:popstate', ['$event'])
onBrowserBackBtnClose(event: Event) {
event.preventDefault();
event.stopPropagation();
this.modalService.dismissAll();
}
This didn't work like many other solutions I tried as mentioned on the internet. I want to decide if anyModal instances active or not. If it is, then close when back button is pressed; otherwise just go back.
CodePudding user response:
just add AngularLocator service and call it on ngOnInit() of any component you need to close the modal!
Angularlocater.onUrlChange(() => this.modalService.dismissAll());
CodePudding user response:
Here is the best I did
lastModalInstance: NgbActiveModal;
modalService.activeInstances.subscribe((activeModals: NgbActiveModal[]) => {
if (activeModals.length > 0) {
if (activeModals.length === 1) {
history.pushState(null, null, window.location.href);
}
this.lastModalInstance = activeModals[activeModals.length - 1];
}
else {
this.lastModalInstance = null;
}
})
@HostListener('window:popstate', ['$event'])
onBrowserBackBtnClose(event: Event) {
event.preventDefault();
if (this.lastModalInstance) {
this.lastModalInstance.close();
}
}