0
0
Angularframework~5 mins

Route guards (canActivate, canDeactivate) in Angular

Choose your learning style9 modes available
Introduction

Route guards help control if a user can enter or leave a page in an Angular app. They keep your app safe and user-friendly.

Prevent users from visiting a page if they are not logged in.
Ask users to confirm before leaving a form with unsaved changes.
Stop navigation to a page if certain conditions are not met.
Protect admin pages from unauthorized access.
Warn users about losing data when they try to leave a page.
Syntax
Angular
export class YourGuard implements CanActivate, CanDeactivate<YourComponent> {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    // return true to allow navigation
    // return false to block navigation
  }

  canDeactivate(
    component: YourComponent,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    // return true to allow leaving the page
    // return false to prevent leaving
  }
}

canActivate runs before entering a route.

canDeactivate runs before leaving a route.

Examples
This guard allows navigation only if the user is logged in.
Angular
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return this.authService.isLoggedIn();
  }
}
This guard asks the user to confirm before leaving a form with unsaved changes.
Angular
export class ConfirmExitGuard implements CanDeactivate<FormComponent> {
  canDeactivate(component: FormComponent): boolean {
    if (component.hasUnsavedChanges()) {
      return confirm('You have unsaved changes. Leave anyway?');
    }
    return true;
  }
}
Sample Program

This example shows two guards: AuthGuard blocks access if not logged in, and ConfirmExitGuard asks for confirmation before leaving a form with unsaved changes.

Angular
import { Injectable } from '@angular/core';
import { CanActivate, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';

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

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  isLoggedIn = false; // simulate login status

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean {
    if (this.isLoggedIn) {
      return true;
    } else {
      alert('You must log in to access this page.');
      return false;
    }
  }
}

@Injectable({ providedIn: 'root' })
export class ConfirmExitGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(
    component: CanComponentDeactivate
  ): boolean | Observable<boolean> | Promise<boolean> {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

// Example component implementing canDeactivate
import { Component } from '@angular/core';

@Component({
  selector: 'app-form',
  template: `<h2>Form Page</h2><button (click)="save()">Save</button>`,
})
export class FormComponent implements CanComponentDeactivate {
  saved = false;

  save() {
    this.saved = true;
    alert('Form saved!');
  }

  canDeactivate(): boolean {
    if (!this.saved) {
      return confirm('You have unsaved changes. Leave anyway?');
    }
    return true;
  }
}
OutputSuccess
Important Notes

Guards must be provided in the Angular dependency injection system.

Use canActivate to protect routes before entering.

Use canDeactivate to warn users before leaving a page.

Summary

Route guards control navigation in Angular apps.

canActivate checks before entering a route.

canDeactivate checks before leaving a route.