Master Angular From Scratch

Learn Angular with clear, interactive, and structured lessons for beginners and developers.

ANGULAR COURSE SYLLABUS
1. Angular Introduction
Angular Introduction Angular History Angular Fundamentals Angular Architecture Component-Based Angular
2. Angular Setup
Angular Setup Introduction Installing Node.js Installing Angular CLI Creating an Angular Application Angular Project Structure
3. Components
Components Overview Component Anatomy Creating Components Component Selector Component Template Component Styles Component Metadata Standalone Components Parent and Child Components Reusable Components
4. Templates
Templates Introduction Template Syntax Template Expressions Template Statements Template Reference Variables ng-template ng-container ngTemplateOutlet Built-in Control Flow
5. Data Binding
Data Binding Introduction Interpolation Binding Property Binding Event Binding Two-Way Data Binding Class & Style Binding
6. Directives
Directives Introduction Attribute Directives Structural Directives Custom Directives
7. Pipes
Pipes Introduction Built-in Pipes Parameterized Pipes Chaining Pipes Custom Pipes
8. Event Handling
Event Handling Introduction DOM Events Event Binding Syntax Event Object Passing Data to Event Handlers
9. Input & Output
Component Communication @Input @Output EventEmitter
10. Lifecycle Hooks
Lifecycle Hooks Introduction ngOnInit ngOnChanges ngAfterViewInit ngOnDestroy
11. Services
Services Introduction Creating Angular Services Using Services in Components Sharing Data Through Services Service Scope
12. Dependency Injection
Dependency Injection Introduction Injecting Dependencies InjectionToken Provider Configuration
13. Routing
Routing Introduction Route Configuration RouterLink & Navigation Route Parameters Child Routes Route Guards
14. Forms
Angular Forms Introduction Template-Driven Forms Reactive Forms Form Validation Form Submission & Error Handling
15. HttpClient
HttpClient Introduction Configuring HttpClient GET Request POST, PUT & DELETE Requests Headers & Parameters HTTP Error Handling
16. Observables
Observables Introduction Creating & Subscribing to Observables Observable Data Streams Observable Operators Subscription Management
17. RxJS
RxJS Introduction RxJS Operators Transformation & Filtering Combining Observables Higher-Order Mapping Subjects
18. API Integration
API Integration Introduction Connecting Angular with REST API Consuming API Data CRUD API Integration API Response & Error Handling

Angular Route Guards

Learn how Angular Route Guards control navigation and protect application routes based on conditions such as authentication, permissions and unsaved changes.

What are Route Guards?

Route Guards are used to control whether a user can enter, leave or access a particular Angular route.

A guard can check a condition before navigation is completed. For example, an application can allow only logged-in users to open an admin dashboard.

Guards are commonly used for authentication, authorization and navigation control.

Route Guard Flow

User Navigation Open Route
→
Route Guard Checks Condition
→
Allowed? Yes / No
→
Route Open / Block

Common Route Guard Types

1
CanActivate

Controls whether a user can activate a route.

2
CanActivateChild

Controls access to child routes.

3
CanDeactivate

Controls whether a user can leave a route.

4
CanMatch

Controls whether a route can be matched.

CanActivate Guard

CanActivate is used when we want to control whether a route can be activated.

A common example is protecting a dashboard so that only authenticated users can access it.

Authentication Guard
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {

    constructor(
        private router: Router
    ) {
    }

    canActivate(): boolean {

        const isLoggedIn = true;

        if (isLoggedIn) {
            return true;
        }

        this.router.navigate(['/login']);

        return false;
    }
}

Applying CanActivate

Route Configuration
const routes: Routes = [

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

];

Navigation Decision

User logged in: Yes

Guard result: Allowed

Dashboard route can be opened.

Authentication Example

Protected Routes
const routes: Routes = [

    {
        path: 'login',
        component: LoginComponent
    },

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

    {
        path: 'admin',
        component: AdminComponent,
        canActivate: [AuthGuard]
    }

];

In this example, the login route is public, while the dashboard and admin routes are protected.

The guard decides whether navigation should continue.

CanActivateChild Guard

CanActivateChild is useful when a parent route contains multiple child routes that should all follow the same access rule.

This avoids repeating the same guard configuration for every child route.

Guard Example
import { Injectable } from '@angular/core';
import { CanActivateChild } from '@angular/router';

@Injectable({
    providedIn: 'root'
})
export class CourseGuard implements CanActivateChild {

    canActivateChild(): boolean {

        return true;

    }
}
Route Configuration
const routes: Routes = [

    {
        path: 'courses',
        component: CoursesComponent,

        canActivateChild: [CourseGuard],

        children: [

            {
                path: 'overview',
                component: OverviewComponent
            },

            {
                path: 'topics',
                component: TopicsComponent
            }

        ]
    }

];

CanDeactivate Guard

CanDeactivate is used when the application needs to decide whether the user can leave the current route.

A common example is preventing a user from leaving a form page when unsaved changes are present.

Component Interface
export interface CanExitPage {

    canExit(): boolean;

}
CanDeactivate Guard
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';

@Injectable({
    providedIn: 'root'
})
export class UnsavedChangesGuard
    implements CanDeactivate<CanExitPage> {

    canDeactivate(
        component: CanExitPage
    ): boolean {

        return component.canExit();

    }
}

CanDeactivate Form Example

Form Component
export class EnquiryComponent
    implements CanExitPage {

    hasUnsavedChanges = true;

    canExit(): boolean {

        if (this.hasUnsavedChanges) {

            return confirm(
                'You have unsaved changes. Leave this page?'
            );

        }

        return true;
    }
}
Route Configuration
const routes: Routes = [

    {
        path: 'enquiry',
        component: EnquiryComponent,
        canDeactivate: [UnsavedChangesGuard]
    }

];

CIIT Training Institute Enquiry

The user starts filling an enquiry form.

User tries to leave: Guard checks unsaved changes

The application can ask the user for confirmation before leaving the page.

CanMatch Guard

CanMatch can control whether Angular should match a route during route matching.

It can be useful when different users should see different route configurations or when a route should not be selected under a particular condition.

Example Guard
import { Injectable } from '@angular/core';
import { CanMatch, Route, UrlSegment } from '@angular/router';

@Injectable({
    providedIn: 'root'
})
export class RoleGuard implements CanMatch {

    canMatch(
        route: Route,
        segments: UrlSegment[]
    ): boolean {

        const isAdmin = true;

        return isAdmin;
    }
}
Route Configuration
const routes: Routes = [

    {
        path: 'admin',
        component: AdminComponent,
        canMatch: [RoleGuard]
    }

];

Guard Decision

Navigation /admin
→
Guard Check User
→
True Allow
→
False Block / Redirect

CIIT Training Institute Example

Imagine a CIIT Training Institute admin area where only authorized users can manage courses and enquiries.

The route guard checks the user's access before opening the protected pages.

Admin Routes
const routes: Routes = [

    {
        path: 'admin',
        component: AdminComponent,
        canActivate: [AuthGuard],

        children: [

            {
                path: 'courses',
                component: CourseManagementComponent
            },

            {
                path: 'enquiries',
                component: EnquiryManagementComponent
            },

            {
                path: 'reports',
                component: ReportsComponent
            }

        ]
    }

];

Protected Area

/admin/courses → Course Management

/admin/enquiries → Enquiry Management

/admin/reports → Reports

Redirecting Unauthorized Users

A guard can redirect an unauthorized user to another route, such as a login page or access-denied page.

This allows the application to provide a controlled navigation experience.

Redirect Example
canActivate(): boolean {

    const isLoggedIn = false;

    if (isLoggedIn) {

        return true;

    }

    this.router.navigate(['/login']);

    return false;
}

Route Guard Comparison

Guard Purpose Typical Use
CanActivate Controls route activation Authentication / Authorization
CanActivateChild Controls child route activation Protected child pages
CanDeactivate Controls leaving a route Unsaved forms
CanMatch Controls route matching Conditional route matching

Important Points

1. Protect Important Routes

Use route guards when access to a route should depend on authentication or another condition.

2. CanActivate Controls Entry

CanActivate checks whether a route can be activated.

3. CanDeactivate Controls Exit

CanDeactivate is useful when the user may need confirmation before leaving a page.

4. Guards Are Navigation Rules

Guards should focus on navigation decisions rather than containing unnecessary application logic.

Route Guard Best Practices

  • Use guards for authentication and authorization requirements.
  • Keep guard logic focused on making navigation decisions.
  • Use CanDeactivate when unsaved changes need protection.
  • Use CanActivateChild for groups of protected child routes.
  • Redirect users to an appropriate route when access is denied.
  • Do not depend on client-side guards alone as the security boundary for backend resources.

Summary

Angular Route Guards control navigation based on conditions such as authentication, authorization and unsaved changes.

Common guards include CanActivate, CanActivateChild, CanDeactivate and CanMatch.

Guards help create controlled navigation flows and protect application routes from unauthorized access.