Day 03 Applied Skills

Angular Router

Angular Router enables multi-page navigation without page reloads. This lesson covers route setup, dynamic parameters, lazy loading, and route guards for a

~1 hour Hands-on Precision AI Academy

Today's Objective

Learn the core concepts of Angular Router and apply them in practical exercises.

01

Setting Up Routes

app-routing.module.ts
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'users/:id', component: UserDetailComponent },
  // Lazy-loaded feature module
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.module')
      .then(m => m.AdminModule),
    canActivate: [AuthGuard]
  },
  { path: '**', redirectTo: '' }  // 404 fallback
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
app.component.html
app.component.html

02

Reading Route Parameters

user-detail.component.ts
user-detail.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({ ... })
export class UserDetailComponent implements OnInit {
  userId: string = '';

  constructor(
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
    // Snapshot: read once on init
    this.userId = this.route.snapshot.paramMap.get('id') ?? '';

    // Observable: react to param changes in same component
    this.route.paramMap.subscribe(params => {
      this.userId = params.get('id') ?? '';
      this.loadUser();
    });
  }

  goBack() { this.router.navigate(['/users']); }
}
03

Route Guards

auth.guard.ts
auth.guard.ts
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 auth: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (this.auth.isLoggedIn()) return true;
    this.router.navigate(['/login']);
    return false;
  }
}
â„šī¸
Lazy loading with loadChildren splits your app into separate JavaScript bundles. Users only download the admin bundle when they navigate to /admin. This dramatically improves initial load time for large apps.

Supporting References & Reading

Go deeper with these external resources.

Docs
Angular Router Official documentation for angular.
→
GitHub
Angular Router Open source examples and projects for Angular Router
→
MDN
MDN Web Docs Comprehensive web technology reference
→

Day 3 Checkpoint

Before moving on, confirm understanding of these key concepts:

Continue To Day 4
Day 4 of the Angular in 5 Days course
→