Git Tutorial

Angular Route Guards

Router guards in Angular allow you to control navigation and protect routes based on specific conditions, such as authentication or permissions. In this tutorial, we’ll add a Route Guard to the previous routing setup to restrict access to the Contact page.

1. Create a Route Guard

Use Angular CLI to generate a guard:

ng generate guard auth

This will create auth.guard.ts. Update the file to implement your guard logic.

src/app/auth.guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
private isAuthenticated = false; // Mock authentication flag

constructor(private router: Router) {}

canActivate(): boolean | Observable<boolean> | Promise<boolean> {
if (this.isAuthenticated) {
return true;
} else {
alert('Access denied. You must be logged in to view this page.');
this.router.navigate(['/']);
return false;
}
}

// Method to toggle authentication (for demonstration purposes)
login() {
this.isAuthenticated = true;
}

logout() {
this.isAuthenticated = false;
}
}

2. Update Routes to Use the Guard

Modify the routes in main.ts to apply the guard to the Contact route.

src/main.ts:

import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, Route } from '@angular/router';
import { AppComponent } from './app/app.component';
import { HomeComponent } from './app/home/home.component';
import { AboutComponent } from './app/about/about.component';
import { ContactComponent } from './app/contact/contact.component';
import { AuthGuard } from './app/auth.guard';

const routes: Route[] = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent, canActivate: [AuthGuard] },
];

bootstrapApplication(AppComponent, {
providers: [provideRouter(routes)],
}).catch((err) => console.error(err));

3. Add Login/Logout Buttons to AppComponent

Provide a way for the user to toggle authentication.

src/app/app.component.ts:

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { AuthGuard } from './auth.guard';

@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
template: `
<nav>
<a routerLink="/" routerLinkActive="active">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>
<a routerLink="/contact" routerLinkActive="active">Contact</a>
</nav>
<button (click)="login()">Login</button>
<button (click)="logout()">Logout</button>
<router-outlet></router-outlet>
`,
styles: [`
nav {
display: flex;
gap: 1rem;
margin-bottom: 1rem;
}
.active {
font-weight: bold;
color: blue;
}
button {
margin-right: 10px;
}
`],
})
export class AppComponent {
constructor(private authGuard: AuthGuard) {}

login() {
this.authGuard.login();
alert('You are now logged in!');
}

logout() {
this.authGuard.logout();
alert('You are now logged out!');
}
}

4. Run and Test the Application

Start the development server:

ng serve

Key Points:

  1. Router Guards: Implemented via the CanActivate interface.
  2. Authentication Logic: Mocked in this example, but you can integrate a real authentication service.
  3. Guard Application: Added to specific routes using the canActivate property.

1 thought on “Angular Route Guards”

  1. Pingback: What Is Angular - Tech Mentor

Leave a Comment

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