angularrouteronbeforeunloadcandeactivatenavigationstart

How to avoid navigating to another page while doing something in current page in Angular


Currently, I am on an HTML page and doing something. And if I mistakenly click another page then it will redirect to that page without getting any user confirmation.

This is my component.

export class MyComponent {    
 constructor(private router: Router, public closeModal: ModalRef,){
 // 1st thing i tried
   router.events.subscribe((val) => {       
      if (val instanceof NavigationStart) {
        const config = {
          class: 'modal-lg, modal-danger',
          keyboard: false,
          animated: true,
          ignoreBackdropClick: true,
          initialState: {
            title: 'Are you sure you want to leave',
            content: `Are you sure you want to leave the page?`
          }
        };
        this.closeModal = this.modalService.show(DeleteConfirmModalComponent, config);
        this.closeModal.content.closeBtnName = 'Close';
      }
    });
}

// 2 thing i tried

@HostListener('window:beforeunload', ['$event'])
  canDeactivate(event: BeforeUnloadEvent): void {
   
    const config = {
      class: 'modal-lg, modal-danger',
      keyboard: false,
      animated: true,
      ignoreBackdropClick: true,
      initialState: {
        title: 'Are you sure you want to leave',
        content: `Are you sure you want to leave the page?`
      }
    };
        this.closeModal = this.modalService.show(DeleteConfirmModalComponent, config);
        this.closeModal.content.closeBtnName = 'Close';

    event.returnValue = false;
  }

}

In 1 st I am getting the confirmation but already navigated to the clicked page rouetlink.

In 2 and I can't see the user confirmation.


Solution

  • RouteGuard's method CanDeactivate is exactly what you need.

    If documentation is too dry, there is an article to help: Angular 10 CanDeactivate.