Sub topic 8
Preventing data loss with canDeactivate
This chapter assumes you can write a functional guard with inject() and know how a Routes array is configured. A canDeactivate guard runs when the user tries to leave a route. It can stop a navigation that would throw away unsaved work.
How canDeactivate differs from canActivate
canActivate asks whether the user may enter a route. canDeactivate asks whether the user may leave the route they are on. Because of that, the router passes the guard the component instance that is about to be destroyed. The guard can ask that component whether it has unsaved changes.
The function receives four arguments: the component, the current route snapshot, the current router state, and the next router state. Most guards use only the first.
A component contract
The guard should not depend on one specific component class. Define a small interface that any component can implement:
import { CanDeactivateFn } from '@angular/router';
export interface HasUnsavedChanges {
hasUnsavedChanges(): boolean;
}
export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) => {
if (!component.hasUnsavedChanges()) {
return true;
}
return window.confirm('You have unsaved changes. Leave this page?');
};window.confirm returns true if the user chooses to leave. That value is returned to the router. A false cancels the navigation, and the user stays on the page.
Implementing the interface
The component decides what "unsaved" means. Here it compares the draft text with the last saved text:
import { Component, signal } from '@angular/core';
import { HasUnsavedChanges } from './unsaved-changes.guard';
@Component({
selector: 'app-editor',
standalone: true,
template: `
<textarea [value]="draft()" (input)="draft.set($any($event.target).value)"></textarea>
<button type="button" (click)="save()">Save</button>
`,
})
export class EditorComponent implements HasUnsavedChanges {
draft = signal('');
private saved = signal('');
hasUnsavedChanges(): boolean {
return this.draft() !== this.saved();
}
save(): void {
this.saved.set(this.draft());
}
}Attaching the guard
Add the guard to the route's canDeactivate array:
import { Routes } from '@angular/router';
import { unsavedChangesGuard } from './unsaved-changes.guard';
export const routes: Routes = [
{
path: 'editor',
canDeactivate: [unsavedChangesGuard],
loadComponent: () => import('./editor.component').then(m => m.EditorComponent),
},
];TypeScript checks that EditorComponent fits the HasUnsavedChanges contract only loosely here, so a typo in the method name can surface as a runtime error. Keep the interface name and method name consistent across components.
Limits to know
- Back button. The browser has already changed the URL when the guard runs. If the guard returns
false, the router restores the previous URL. - Blocking dialogs.
window.confirmis simple but hard to style and test. A guard can instead return anObservable<boolean>orPromise<boolean>from a custom dialog service. - Same-route changes. If only a parameter changes and the component is reused, the guard still runs by default. It can compare
currentStateandnextStateto skip the prompt when appropriate.
Exercise
A user edits a form and then closes the browser tab. Will an Angular canDeactivate guard show your confirmation prompt? What can you add to handle it?
Show answer
No. canDeactivate runs only for router navigations, and closing a tab is not one. Add a window beforeunload event listener that warns the user when the component has unsaved changes.