Sub topic 8
Preventing data loss with canDeactivate
This chapter assumes you can write a functional canActivate guard, know how inject() works inside one, and have a component with a form. By the end you will be able to stop a user from leaving a page with unsaved edits, ask for confirmation, and cover the cases the router cannot see.
The problem canDeactivate solves
A user fills in half a form, then clicks a navigation link or presses the browser's back button. By default the router tears down the component and the edits are gone. A canDeactivate guard runs before the router leaves the current route. It can allow the navigation, cancel it, or redirect.
The other guards you have seen decide whether the user may enter a route. canDeactivate decides whether the user may leave one. Because of that, it receives the component instance that is about to be destroyed.
The signature
A functional deactivation guard has the type CanDeactivateFn<T>, where T is the type of the component being left. Its parameters are:
| Parameter | What it holds |
|---|---|
| `component` | The instance of the component on the route being left |
| `currentRoute` | `ActivatedRouteSnapshot` of the route being left |
| `currentState` | `RouterStateSnapshot` of the current URL |
| `nextState` | `RouterStateSnapshot` of the URL the user is heading to |
It can return boolean, a UrlTree, or a RedirectCommand, or a Promise or Observable of any of those. These are the same return values as for other guards. Returning false cancels the navigation and the user stays where they are.
A minimal guard
Define a small interface that a component implements, and type the guard against that interface instead of a concrete class. This lets one guard serve every editable page.
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?');
};If the component is clean, navigation continues. If it is dirty, the browser's confirm dialog returns true (leave) or false (stay).
Wiring it into the route
Attach the guard with the canDeactivate array on the route that renders the editable component.
import { Routes } from '@angular/router';
import { unsavedChangesGuard } from './unsaved-changes.guard';
export const routes: Routes = [
{
path: 'profile/edit',
canDeactivate: [unsavedChangesGuard],
loadComponent: () =>
import('./profile-edit.component').then(m => m.ProfileEditComponent),
},
];The component must implement the interface, or the guard fails to type-check. Here it tracks edits with a reactive form:
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { HasUnsavedChanges } from './unsaved-changes.guard';
@Component({
selector: 'app-profile-edit',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="save()">
<input formControlName="name" />
<button type="submit">Save</button>
</form>
`,
})
export class ProfileEditComponent implements HasUnsavedChanges {
private fb = inject(FormBuilder);
form = this.fb.nonNullable.group({ name: '' });
hasUnsavedChanges(): boolean {
return this.form.dirty;
}
save(): void {
// Persist the data, then mark the form clean so the guard allows leaving.
this.form.markAsPristine();
}
}The save() method must reset the dirty state. If it doesn't, users are asked to confirm after saving, which is the most common bug with this pattern.
Using a custom dialog
window.confirm blocks the page and cannot be styled. A real application usually opens its own dialog, which is asynchronous. Because guards may return an Observable<boolean>, the router simply waits for the answer.
This example assumes a ConfirmDialogService in your app whose confirm(message) method returns an Observable<boolean> that emits once. The service is not part of Angular.
import { inject } from '@angular/core';
import { CanDeactivateFn } from '@angular/router';
import { of } from 'rxjs';
import { ConfirmDialogService } from './confirm-dialog.service';
import { HasUnsavedChanges } from './unsaved-changes.guard';
export const dialogUnsavedGuard: CanDeactivateFn<HasUnsavedChanges> = (component) => {
if (!component.hasUnsavedChanges()) {
return of(true);
}
return inject(ConfirmDialogService).confirm('Discard your unsaved changes?');
};The observable must complete or emit. The router takes the first emitted value, so a dialog stream that never emits leaves the navigation hanging with no feedback.
What the router does when you cancel
When a guard returns false, the router emits a NavigationCancel event and leaves the current component in place. For a link click this is invisible. For the back button it is trickier. The browser has already changed the URL by the time the guard runs, and the router has to restore it. This can leave the address bar and history stack briefly out of step, and repeated cancellations may leave an extra history entry. Test the back-button path by hand.
Edge cases to know
- The component can be null. If the route uses
loadChildrenor has no component of its own, there is no instance to inspect. PutcanDeactivateon the route that directly renders the editable component. - Parameter changes can trigger it. By default, guards re-run when route parameters change. Moving from
/profile/1/editto/profile/2/editreuses the component, but the guard still runs and can warn about unsaved edits. This is usually what you want. - Programmatic navigation is covered.
router.navigate()androuterLinkboth go through the same guards, so you need no extra code for them. - Redirect after saving. If
save()callsrouter.navigate()and then marks the form pristine, the guard sees a dirty form and prompts the user. Mark the form pristine before navigating. - Use
nextStateto skip prompts. If some destinations are harmless, such as a help panel, readnextState.urland returntrueearly.
import { CanDeactivateFn } from '@angular/router';
import { HasUnsavedChanges } from './unsaved-changes.guard';
export const selectiveGuard: CanDeactivateFn<HasUnsavedChanges> = (
component,
currentRoute,
currentState,
nextState,
) => {
if (nextState.url.startsWith('/help')) {
return true;
}
return !component.hasUnsavedChanges() || window.confirm('Discard changes?');
};What canDeactivate cannot catch
The router only controls navigations inside the Angular app. Closing the tab, reloading, or typing a different site's address never reaches the guard. For those, listen to the browser's beforeunload event and ask the browser to show its own warning.
import { HostListener } from '@angular/core';
// Inside the same component class:
@HostListener('window:beforeunload', ['$event'])
onBeforeUnload(event: BeforeUnloadEvent): void {
if (this.hasUnsavedChanges()) {
event.preventDefault();
}
}Browsers show a generic message and ignore any custom text. Use both mechanisms together: the guard for in-app navigation and beforeunload for leaving the app.
Common mistakes
- Forgetting to reset the dirty flag after a successful save, so users are prompted needlessly.
- Typing the guard against a concrete component class, which forces one guard per page.
- Returning an observable that never emits, which freezes the navigation.
- Putting the guard on a parent route when the form lives in a child component.
Exercise
A user saves a profile form and your code calls router.navigate(['/profile']) right away. They still see the "unsaved changes" prompt. What is the likely cause, and how do you fix it?
Show answer
The form is still marked dirty when the navigation starts, so hasUnsavedChanges() returns true and the guard prompts. Call form.markAsPristine() (or reset the form with the saved values) after the save succeeds and before calling router.navigate().
Exercise
Why does a canDeactivate guard not protect against the user closing the browser tab, and what do you use instead?
Show answer
The router only runs guards for navigations it handles inside the Angular app. Closing a tab or reloading is handled by the browser. Listen for the window "beforeunload" event and call event.preventDefault() when there are unsaved changes, so the browser shows its own confirmation.