What is canDeactivate Guard in Angular: Explanation and Example
canDeactivate guard in Angular is a feature that lets you control if a user can leave a route or component. It helps prevent losing unsaved changes by asking for confirmation before navigating away from the current page.How It Works
The canDeactivate guard acts like a gatekeeper when you try to leave a page in an Angular app. Imagine you are filling out a form and accidentally click a link to go somewhere else. The guard can stop this and ask, "Are you sure you want to leave?" This way, you don't lose your work.
Technically, Angular calls a method you define in your component or service before changing the route. If this method returns true, navigation proceeds. If it returns false, navigation is canceled. You can also return a Promise or Observable for asynchronous confirmation, like showing a popup.
Example
canDeactivate guard that asks the user to confirm leaving a form with unsaved changes.import { Injectable } from '@angular/core'; import { CanDeactivate } from '@angular/router'; import { Observable } from 'rxjs'; export interface CanComponentDeactivate { canDeactivate: () => boolean | Observable<boolean> | Promise<boolean>; } @Injectable({ providedIn: 'root' }) export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> { canDeactivate( component: CanComponentDeactivate ): boolean | Observable<boolean> | Promise<boolean> { return component.canDeactivate ? component.canDeactivate() : true; } } // In your component: import { Component } from '@angular/core'; @Component({ selector: 'app-edit-form', template: ` <h2>Edit Form</h2> <input [(ngModel)]="formData" placeholder="Type something..." /> ` }) export class EditFormComponent implements CanComponentDeactivate { formData = ''; saved = false; canDeactivate(): boolean { if (!this.saved && this.formData) { return confirm('You have unsaved changes. Leave anyway?'); } return true; } } // In your routing module: // { path: 'edit', component: EditFormComponent, canDeactivate: [CanDeactivateGuard] }
When to Use
Use canDeactivate guards when you want to protect users from losing data by accidentally leaving a page. Common cases include:
- Forms where users enter data that is not yet saved.
- Multi-step wizards where leaving early might lose progress.
- Editing screens where changes should be confirmed before exit.
This guard improves user experience by preventing accidental data loss and giving users a chance to save or cancel navigation.
Key Points
- canDeactivate guards run before leaving a route.
- They can return boolean, Promise, or Observable to allow async confirmation.
- Implement a
canDeactivatemethod in your component to define the logic. - Use it to prevent losing unsaved changes or important state.
- Works well with Angular's router to control navigation flow.