0
0
AngularConceptBeginner · 3 min read

What is canDeactivate Guard in Angular: Explanation and Example

The 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

This example shows a simple canDeactivate guard that asks the user to confirm leaving a form with unsaved changes.
typescript
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] }
Output
When navigating away from the EditFormComponent with unsaved changes, a browser confirmation dialog appears asking 'You have unsaved changes. Leave anyway?'. Navigation proceeds only if the user confirms.
🎯

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 canDeactivate method 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.

Key Takeaways

The canDeactivate guard prevents users from accidentally leaving a page with unsaved changes.
It works by calling a method in your component that returns true or false to allow or block navigation.
You can show a confirmation dialog inside the canDeactivate method to ask users before leaving.
Use canDeactivate guards on forms, editors, or any page where data loss is a risk.
The guard supports synchronous and asynchronous checks using boolean, Promise, or Observable.