Back to Curriculum

Routing and Navigation

📚 Lesson 4 of 8 ⏱️ 50 min

Routing and Navigation

50 min

Angular Router enables single-page application (SPA) navigation by mapping URLs to components without full page reloads. The router manages application state, browser history, and navigation. Routes define which component displays for each URL path. Understanding routing is essential for building multi-page Angular applications that feel like native apps with smooth navigation and proper browser history support.

Routes are defined in a routes array, mapping URL paths to components. Each route can have a path, component, children (nested routes), data (static data), and guards. The router matches the current URL to routes and displays the corresponding component in a `<router-outlet>`. Route parameters (`:id`) and query parameters (`?key=value`) enable dynamic routing. Understanding route configuration helps you design application navigation structure.

Router outlet (`<router-outlet>`) is a placeholder where Angular displays the component for the current route. You can have multiple outlets for named routes, enabling complex layouts. Navigation happens programmatically using `Router.navigate()` or declaratively using `routerLink` directive. The router updates the browser URL and history, enabling back/forward button support. Understanding router outlet and navigation enables you to build proper SPA navigation.

Route guards protect routes by controlling access based on conditions. Guards can prevent navigation (CanActivate), prevent leaving a route (CanDeactivate), resolve data before activation (Resolve), and load modules lazily (CanLoad). Guards are essential for authentication, authorization, and data loading. Understanding guards helps you secure routes and improve user experience by loading data before navigation completes.

Lazy loading enables loading feature modules on-demand, improving initial load time. Routes can specify a module to load lazily using `loadChildren`. This splits your application into smaller chunks that load only when needed. Route parameters and query parameters enable passing data through URLs. ActivatedRoute service provides access to route data, parameters, and query parameters in components. Understanding these features helps you build efficient, data-driven navigation.

Best practices include organizing routes logically, using lazy loading for feature modules, protecting routes with guards, using route parameters for dynamic content, and handling route errors gracefully. Navigation should be intuitive, fast, and provide proper feedback. Understanding routing enables you to build professional Angular applications with proper navigation and state management.

Key Concepts

  • Angular Router enables SPA navigation without page reloads.
  • Routes map URL paths to components.
  • Router outlet displays the component for the current route.
  • Route guards protect routes based on conditions.
  • Lazy loading improves performance by loading modules on-demand.

Learning Objectives

Master

  • Setting up Angular routing with route configuration
  • Implementing navigation with routerLink and Router service
  • Using route parameters and query parameters
  • Creating and using route guards for route protection

Develop

  • SPA navigation and routing thinking
  • Understanding application state and URL management
  • Designing intuitive navigation structures

Tips

  • Use routerLink directive for declarative navigation in templates.
  • Use Router.navigate() for programmatic navigation in components.
  • Use route guards to protect routes requiring authentication.
  • Implement lazy loading for feature modules to improve performance.

Common Pitfalls

  • Forgetting to import RouterModule, causing routing to not work.
  • Not handling route errors, leaving users on broken pages.
  • Not using route guards, leaving routes unprotected.
  • Loading all modules eagerly, causing slow initial load times.

Summary

  • Angular Router enables SPA navigation between views.
  • Routes map URLs to components and define navigation structure.
  • Router outlet displays components for the current route.
  • Route guards protect routes and control access.
  • Understanding routing is essential for multi-page Angular applications.

Exercise

Set up routing with multiple components and route parameters.

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { UserListComponent } from './user-list.component';
import { UserDetailComponent } from './user-detail.component';
import { AboutComponent } from './about.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'users', component: UserListComponent },
  { path: 'users/:id', component: UserDetailComponent },
  { path: 'about', component: AboutComponent },
  { path: '**', redirectTo: '' }
];

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

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/users">Users</a>
      <a routerLink="/about">About</a>
    </nav>
    
    <router-outlet></router-outlet>
  `,
  styles: [`
    nav {
      background: #333;
      padding: 10px;
    }
    nav a {
      color: white;
      text-decoration: none;
      margin-right: 20px;
    }
    nav a:hover {
      color: #ddd;
    }
  `]
})
export class AppComponent { }

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

@Component({
  selector: 'app-user-detail',
  template: `
    <div *ngIf="user" class="user-detail">
      <h2>{{ user.name }}</h2>
      <p>Email: {{ user.email }}</p>
      <p>Age: {{ user.age }}</p>
      <button (click)="goBack()">Back to Users</button>
    </div>
  `,
  styles: [`
    .user-detail {
      padding: 20px;
      border: 1px solid #ddd;
      border-radius: 5px;
      margin: 20px;
    }
  `]
})
export class UserDetailComponent implements OnInit {
  user: User | undefined;

  constructor(
    private route: ActivatedRoute,
    private userService: UserService
  ) {}

  ngOnInit() {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.userService.getUserById(id).subscribe(user => {
      this.user = user;
    });
  }

  goBack() {
    // Navigate back
    window.history.back();
  }
}

Exercise Tips

  • Use routerLinkActive to highlight active navigation links.
  • Create route guards to protect routes requiring authentication.
  • Use lazy loading with loadChildren for feature modules.
  • Access route parameters using ActivatedRoute service.

Code Editor

Output