En la aplicación Angular (ver 11) cuando se presiona el botón Atrás o se llama a location.back() si ngbModal está activo, quiero que se cierre. Después de la investigación que hice, se me ocurrió algo como esto:
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(); }Esto no funcionó como muchas otras soluciones que probé como se menciona en Internet. Quiero decidir si alguna instancia Modal está activa o no. Si es así, cierre cuando se presione el botón Atrás; de lo contrario, simplemente regrese.
simplemente agregue el servicio AngularLocator y llámelo en ngOnInit() de cualquier componente que necesite para cerrar el modal.
Angularlocater.onUrlChange(() => this.modalService.dismissAll());Aquí está lo mejor que hice
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(); } }