Angular › Router Guards & Resolvers
What is the canDeactivate guard used for, and how would you use it to warn a user about unsaved changes?
IntermediateAnswer
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.