Routing and Navigation

Mastering Route Guards: Secure and Control Angular Navigation

Learning Outcome

5

Control navigation flow securely

4

Implement Auth Guard

3

Explore different types of guards

2

Learn how to protect routes

1

Understand Route Guards in Angular

Analogy

Security guard checks ID before entry

Think of a secured office building:

Analogy

Mapping :

Same concept in Angular routing.

User → Visitor

Route → Room

Guard → Security

If authorized → Allow entry

 If not → Block access

Why Route Guards are Important

In real applications :

Some actions need confirmation

Some data must be loaded before navigation

Some pages require authentication

Without guards :

Route Guards help :

Unauthorized access possible

Poor security

Bad user experience

Secure routes

Control navigation

Improve application flow

What are Route Guards?

Route Guards are used to control navigation.

They decide :

Should data load before route?

Can user leave route?

Can user access route?

Types of Route Guards

CanActivate → Allow/deny route access

CanDeactivate → Prevent leaving a route

CanActivateChild → Protect child routes

CanLoad → Prevent module loading

Resolve → Load data before route

CanActivate Guard (Auth Guard)

Used for authentication.

syntax

import { CanActivate } from '@angular/router';

export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return true; // allow or deny
  }
}

Now only authorized users can access.

Example: Auth Logic

canActivate(): boolean {
  const isLoggedIn = localStorage.getItem('user');

  if (isLoggedIn) {
    return true;
  }

  return false;
}

Protecting Routes using Guard

const routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard]
  }
];

CanDeactivate Guard

Used to prevent leaving a page.

Example :

canDeactivate(): boolean {
  return confirm("Are you sure?");
}

Unsaved form

Confirmation dialog

Resolve Guard & CanLoad Guard

Used to load data before route.

resolve() {
  return this.apiService.getData();
}

Ensures data is ready before page loads.

Resolve Guard :

Prevents module loading.

CanLoad Guard :

Used in lazy loading

canLoad(): boolean {
  return false;
}

Summary

4

Guards improve application security and flow

3

AuthGuard is commonly used for authentication

2

They control access, exit, and data loading

1

Route Guards are used to secure Angular routes

Quiz

Which guard loads data before route?

A. Resolve

B. CanActivate

C. CanLoad

D. GuardInit

Quiz-Answer

Which guard loads data before route?

A. Resolve

B. CanActivate

C. CanLoad

D. GuardInit