Back to course

Route Guards: CanDeactivate (Form Persistence)

The Complete Angular Developer: From Zero to Hero

38. Route Guards: CanDeactivate (Form Persistence)

CanDeactivate prevents a user from leaving a route, typically used to confirm if they want to discard unsaved changes in a form.

1. Defining the Deactivatable Interface

We define an interface that components using this guard must implement.

typescript // can-deactivate.guard.ts import { Observable } from 'rxjs';

export interface CanComponentDeactivate { canDeactivate: () => Observable | Promise | boolean; }

// The guard implements CanDeactivate using the interface type @Injectable({ providedIn: 'root' }) export class ChangesGuard implements CanDeactivate { canDeactivate(component: CanComponentDeactivate) { return component.canDeactivate ? component.canDeactivate() : true; } }

2. Implementing the Interface in the Component

The component must provide the canDeactivate method, which contains the logic to check for unsaved changes.

typescript // profile-editor.component.ts export class ProfileEditorComponent implements CanComponentDeactivate { hasUnsavedChanges: boolean = true;

canDeactivate(): boolean { if (this.hasUnsavedChanges) { return confirm('WARNING: You have unsaved changes. Discard?'); } return true; } }

3. Applying the Guard

typescript import { ChangesGuard } from './can-deactivate.guard';

const routes: Routes = [ { path: 'profile', component: ProfileEditorComponent, canDeactivate: [ChangesGuard] // Applies the guard on exit attempt } ];

If the component returns false, navigation is aborted, and the user remains on the current page.