How to show modal confirmation in CanDeactivate in Angular2 application?

3.7k views Asked by At

I have an Angular2 application. One of its components implements CanDeactivate interface to confirm user's navigation away from the page. Here is the implementation of the route guard:

export class DeactivateGuard implements CanDeactivate<MyComponent> {
  canDeactivate(component: MyComponent) {
  let can = component.canDeactivate();
  return can;
  }
}

And here is the components's code:

canDeactivate() {
if (confirm("Are you sure you want to navigate away?")) {      
  return true;
}
else {
  return false;
}
}

Now, I want to show a custom modal window instead of browser's confirmation box. I have built such window with Telerik's Kendo UI:

<kendo-dialog title="Please confirm" *ngIf="userConfirm">
    Are you sure you want to navigate away?
    <kendo-dialog-actions>
        <button kendoButton class="k-button" (click)="closeConfirm('no')">No</button>
        <button kendoButton class="k-button" (click)="closeConfirm('yes')" primary="true">Yes</button>
    </kendo-dialog-actions>
</kendo-dialog>

This modal window works if I set userConfirm = true anywhere in code, except for in canDeactivate() method.

canDeactivate() {
this.userConfirm = true; //Does not work. The modal does not show up.
}

How can I use this modal window to get user's input?

Thank you.

2

There are 2 answers

1
dockleryxk On

I am not sure how Kendo works, but when just using confirm() you would return the function in your canDeactivate() function like so:

canDeactivate() {
  return confirm("Are you sure you want to navigate away?");
}

You can read more about canDeactivate() here.

2
Daniel Kucal On

I think you are losing the scope when executing component.canDeactivate(); from your auth guard. Try this instead:

export class DeactivateGuard implements CanDeactivate<MyComponent> {
  canDeactivate(component: MyComponent) {
    return (() => component.canDeactivate())();
  }
}