Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Best way to close ngbModal instances when back button is pressed

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

just add AngularLocator service and call it on ngOnInit() of any component you need to close the modal!

Angularlocater.onUrlChange(() => this.modalService.dismissAll());
about 4 years ago · Juan Pablo Isaza Report

0

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();
    }
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!