Advertisement
Intermediate Angular, Router Guards & Resolvers

What is the canDeactivate guard used for, and how would you use it to warn a user about unsaved changes?

Short answer

The canDeactivate guard runs before a user navigates away from a route, letting you check whether it is actually safe to leave, such as prompting the user to confirm if they have unsaved changes in a form that would otherwise be lost.

Save Angular mock interview
Advertisement
AModel answer
The canDeactivate guard runs before a user navigates away from a route, letting you check whether it is actually safe to leave, such as prompting the user to confirm if they have unsaved changes in a form that would otherwise be lost.
export const unsavedChangesGuard: CanDeactivateFn<EditFormComponent> = (component) => {
  if (component.hasUnsavedChanges()) {
    return confirm('You have unsaved changes, leave anyway?');
  }
  return true;
};

{ path: 'edit', component: EditFormComponent, canDeactivate: [unsavedChangesGuard] }
Real-world example
A blog editor warns a writer with a confirmation dialog if they try to navigate away from an article with unsaved changes, using a canDeactivate guard to prevent accidentally losing their work.
Likely follow-ups
  • What happens if the component being navigated away from does not implement the expected interface?
  • How would you build a more polished custom confirmation dialog instead of the plain browser confirm popup?
Related topics