#angular #routing #navigation #guards

Day 4 โ€” Angular Routing, Navigation, Route Params, Guards & Lazy Loading

๐Ÿ“˜ Day 4 โ€” Angular Routing, Navigation, Route Params, Guards & Lazy Loading

Zero to Hero โ€” Hands-on, Blog-Style Tutorial

By the end of Day 4, youโ€™ll know:

  • โœ”๏ธ How Angular routing works
  • โœ”๏ธ How to create pages
  • โœ”๏ธ How to navigate between pages
  • โœ”๏ธ How to extract route parameters
  • โœ”๏ธ How to use signals with routing
  • โœ”๏ธ How to add navigation menus
  • โœ”๏ธ How to create a guard (AuthGuard)
  • โœ”๏ธ How to lazy-load standalone components

Letโ€™s build a real multi-page Angular app! ๐Ÿš€


๐ŸŸฆ 1. What Is Angular Routing?

Routing allows Angular to show different components based on URL.

Example:

URLScreen
/Home page
/aboutAbout page
/users/5User detail page
/dashboardAdmin dashboard (maybe protected)

Routing = SPA navigation without page reloads.


๐ŸŸฉ 2. Create Pages (Standalone Components)

Letโ€™s build 3 pages:

ng g component pages/home --standalone
ng g component pages/about --standalone
ng g component pages/user-details --standalone

Now you have:

pages/
 โ”œโ”€ home/
 โ”œโ”€ about/
 โ””โ”€ user-details/

๐ŸŸง 3. Define Routes (In app.routes.ts)

Open: src/app/app.routes.ts

Replace with:

import { Routes } from '@angular/router';
import { HomeComponent } from './pages/home/home.component';
import { AboutComponent } from './pages/about/about.component';
import { UserDetailsComponent } from './pages/user-details/user-details.component';

export const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'users/:id', component: UserDetailsComponent }
];
  • โœ”๏ธ :id is a route parameter
  • โœ”๏ธ '' means โ€œhome/root routeโ€

๐ŸŸฅ 4. Add Router to AppComponent

Open: app.component.ts

Add router imports:

import { RouterOutlet, RouterLink } from '@angular/router';

@Component({
  ...
  imports: [RouterOutlet, RouterLink],
})
export class AppComponent {}

Update template: app.component.html

<nav>
  <a routerLink="">Home</a>
  <a routerLink="about">About</a>
  <a routerLink="users/1">User #1</a>
</nav>

<hr />

<router-outlet></router-outlet>
  • โœ”๏ธ routerLink = navigation
  • โœ”๏ธ router-outlet = where pages display

Now try clicking the links!


๐ŸŸฉ 5. Extracting Route Parameters (ActivatedRoute)

In user-details.component.ts:

import { Component, inject, signal } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-user-details',
  standalone: true,
  templateUrl: './user-details.component.html',
})
export class UserDetailsComponent {
  route = inject(ActivatedRoute);
  userId = signal('');

  constructor() {
    this.route.paramMap.subscribe(params => {
      this.userId.set(params.get('id') ?? '');
    });
  }
}

Template:

<h2>User Details</h2>
<p>User ID from URL: {{ userId() }}</p>

Now navigate to: /users/99

You will see:

User ID from URL: 99

  • โœ”๏ธ You learned dynamic routing
  • โœ”๏ธ You used signals to store route data

๐ŸŸฆ 6. Programmatic Navigation (Router)

In HomeComponent, add a โ€œGo to userโ€ button.

home.component.ts:

import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  standalone: true,
  templateUrl: './home.component.html',
})
export class HomeComponent {
  router = inject(Router);

  goToUser() {
    this.router.navigate(['/users/5']);
  }
}

home.component.html:

<h2>Welcome to Home</h2>

<button (click)="goToUser()">Go to User 5</button>
  • โœ”๏ธ router.navigate() for logic-based navigation

๐ŸŸฅ 7. Add Active Route Styling (routerLinkActive)

In your nav:

<nav>
  <a routerLink="" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Home</a>
  <a routerLink="about" routerLinkActive="active">About</a>
  <a routerLink="users/1" routerLinkActive="active">User #1</a>
</nav>

Add css:

.active {
  font-weight: bold;
  color: #1976d2;
}
  • โœ”๏ธ Auto-highlighting of current page
  • โœ”๏ธ Common in dashboards

๐ŸŸซ 8. Route Guards โ€” Protecting Routes

Letโ€™s build AuthGuard.

Generate:

ng g guard auth --standalone

Open: auth.guard.ts:

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

export const authGuard: CanActivateFn = () => {
  const isLoggedIn = false; // change later โ€” will use real auth

  return isLoggedIn ? true : false;
};

Now protect a route:

{
  path: 'dashboard',
  loadComponent: () =>
    import('./pages/dashboard/dashboard.component').then(m => m.DashboardComponent),
  canActivate: [authGuard]
}

Try opening /dashboard โ†’ you get blocked โœ”๏ธ

Later (Day 8), we build real authentication.


๐ŸŸง 9. Lazy Loading (Modern Standalone Version)

Lazy loading is critical in large apps.

Letโ€™s lazy load the About page.

Change:

{ path: 'about', component: AboutComponent }

To:

{
  path: 'about',
  loadComponent: () =>
    import('./pages/about/about.component').then(m => m.AboutComponent)
}
  • โœ”๏ธ No NgModule
  • โœ”๏ธ Page loads only when user navigates
  • โœ”๏ธ Angular 17+ best practice

๐ŸŸฆ 10. Real-World Example: Nested Routes

Letโ€™s add:

  • /users/:id/profile
  • /users/:id/settings

Inside routes:

{
  path: 'users/:id',
  children: [
    { path: 'profile', loadComponent: () => import('./pages/user-profile/user-profile.component').then(m => m.UserProfileComponent) },
    { path: 'settings', loadComponent: () => import('./pages/user-settings/user-settings.component').then(m => m.UserSettingsComponent) }
  ]
}

This structure mirrors real enterprise apps.


๐ŸŽ‰ End of Day 4 โ€” What You Learned

Today you covered A LOT:

  • โœ”๏ธ Routing basics
  • โœ”๏ธ routerLink & router-outlet
  • โœ”๏ธ Route parameters (:id)
  • โœ”๏ธ ActivatedRoute + signals
  • โœ”๏ธ Programmatic navigation
  • โœ”๏ธ Active route highlighting
  • โœ”๏ธ Guards (canActivate)
  • โœ”๏ธ Lazy loading
  • โœ”๏ธ Nested routes
  • โœ”๏ธ Building multiple pages

You now understand exactly how modern Angular apps are structured.

This is huge. Youโ€™re leveling up fast ๐Ÿ’ช.


๐Ÿงช Day 4 Challenge

Create:

๐Ÿ‘‰ A โ€œProductsโ€ section with:

  1. /products โ†’ ProductListComponent
  2. /products/:id โ†’ ProductDetailsComponent
  3. Fetch the product ID
  4. Add a โ€œBackโ€ button using programmatic navigation
  5. Protect /products/:id using authGuard