Prevent navigation in ngDestroy angular

724 views Asked by At

I want to prevent the user from navigating away from the current page if the form is dirty. While this works with CanDeactivate guard, the problem is when I try to move on to another child component of the same parent, without a route change. The only thing common between these two scenarios is that, in both cases, ngOnDestroy() is being hit. But, unfortunately, opening the confirmation dialog (mat-dialog) in ngOnDestroy does not prevent the navigation from happening in the background. Is there a possible solution for this?

    ngOnDestroy() {

    if (this.form.dirty) {
      const matDialogConfig = new MatDialogConfig();
      .......
      let dialogRef = this.dialog.open(dialogComponent, matDialogConfig);
      dialogRef.afterClosed().subscribe(result => {
        if (result) {
          //submit form
        }
      }, () => {
      });
    }
  }
0

There are 0 answers