Connect with us

Blog

Angular Guard: A Complete Guide to Route Protection

Published

on

Angular Guard

An Angular Guard is a feature that helps protect routes in an Angular application. It allows developers to control navigation and decide whether a user can access a specific route based on conditions like authentication, user roles, or permissions.

Why Use Angular Guards?

Angular Guards are essential for:

  • Security: Prevent unauthorized access to protected routes.
  • User Experience: Restrict access to only relevant content.
  • Performance: Prevent unnecessary route loading.
  • Custom Navigation Control: Allow or restrict navigation based on logic.

Types of Angular Guards

Angular provides five types of route guards, each serving a different purpose:

1. CanActivate

  • Controls access to a route.
  • Example: Prevents users from accessing the dashboard without logging in.

2. CanActivateChild

  • Works like CanActivate but applies to child routes.
  • Example: Restricts access to admin-related child routes.

3. CanDeactivate

  • Asks users for confirmation before leaving a route.
  • Example: Prompts users to save changes before exiting a form page.

4. Resolve

  • Fetches data before loading a route.
  • Example: Preloads user details before opening a profile page.

5. CanLoad

  • Prevents lazy-loaded modules from being loaded unless conditions are met.
  • Example: Loads an admin panel module only if the user is an admin.

How to Implement Angular Guards

1. Creating a Guard in Angular

To create a guard, use the Angular CLI:

sh

CopyEdit

ng generate guard auth

This command generates an authentication guard (auth.guard.ts).

2. Implementing CanActivate Guard

Modify auth.guard.ts to check user authentication:

typescript

CopyEdit

import { Injectable } from ‘@angular/core’;

import { CanActivate, Router } from ‘@angular/router’;

import { AuthService } from ‘./auth.service’;

@Injectable({

  providedIn: ‘root’,

})

export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {

    if (this.authService.isLoggedIn()) {

      return true;

    } else {

      this.router.navigate([‘/login’]);

      return false;

    }

  }

}

This checks if the user is logged in before granting access.

3. Applying Guard to Routes

Add the guard to app-routing.module.ts:

typescript

CopyEdit

import { NgModule } from ‘@angular/core’;

import { RouterModule, Routes } from ‘@angular/router’;

import { DashboardComponent } from ‘./dashboard/dashboard.component’;

import { AuthGuard } from ‘./auth.guard’;

const routes: Routes = [

  { path: ‘dashboard’, component: DashboardComponent, canActivate: [AuthGuard] },

];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule],

})

export class AppRoutingModule {}

This prevents unauthorized users from accessing the dashboard.

4. Implementing CanDeactivate Guard

Use a guard to confirm before navigating away:

typescript

CopyEdit

import { Injectable } from ‘@angular/core’;

import { CanDeactivate } from ‘@angular/router’;

import { Observable } from ‘rxjs’;

export interface CanComponentDeactivate {

  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;

}

@Injectable({

  providedIn: ‘root’,

})

export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {

  canDeactivate(component: CanComponentDeactivate): boolean {

    return component.canDeactivate ? component.canDeactivate() : true;

  }

}

Apply it to a route:

typescript

CopyEdit

const routes: Routes = [

  { path: ‘edit’, component: EditComponent, canDeactivate: [CanDeactivateGuard] },

];

This ensures users confirm before leaving the page.

Best Practices for Using Angular Guards

Angular Guard
  • Use Guards for Role-Based Access: Restrict pages based on user roles.
  • Keep Guards Lightweight: Avoid heavy logic inside guards.
  • Combine Multiple Guards: Use CanActivate and CanLoad together for better security.
  • Handle Edge Cases: Ensure users cannot bypass authentication by manipulating the URL.

Conclusion

Angular Guards are a powerful tool for managing navigation and protecting routes. By implementing CanActivate, CanDeactivate, CanLoad, and other guards, you can enhance security, improve user experience, and ensure a smooth workflow in your Angular applications.

FAQs

What is the main purpose of Angular Guards?
Angular Guards help control navigation and protect routes based on authentication, authorization, and other conditions.

How do I prevent users from accessing a page without logging in?
Use the CanActivate guard to check user authentication before allowing access.

What is the difference between CanActivate and CanLoad?
CanActivate controls access to a route, while CanLoad prevents an entire module from being loaded unless conditions are met.

How can I prompt users before they leave a page?
Use the CanDeactivate guard to ask for confirmation before navigating away.

Can I use multiple guards on a single route?
Yes, you can apply multiple guards to a route by listing them in the canActivate or canDeactivate properties in the route configuration.

Continue Reading
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending