1

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.

IAfanasov
  • 4,775
  • 3
  • 27
  • 42
Hans
  • 308
  • 7
  • 20

2 Answers2

2

RouteGuard's method CanDeactivate is exactly what you need.

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

IAfanasov
  • 4,775
  • 3
  • 27
  • 42
0

Use async - await methods

so you can the navigation part to wait until the process/method completed