Episode 18 of 27

Route Params

Work with dynamic route parameters — capture URL params, use ActivatedRoute, and build detail pages.

Route Params

Route parameters let you create dynamic routes — URLs that contain variable data like user IDs, product slugs, or article names.

Defining a Route with Parameters

// app-routing.module.ts
const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'users', component: UserListComponent },
    { path: 'users/:id', component: UserDetailComponent },  // :id is a parameter
    { path: 'posts/:category/:slug', component: PostComponent }, // Multiple params
];

The colon : prefix indicates a route parameter. :id matches any value in that URL segment.

Linking to Dynamic Routes

<!-- In a template: -->
<a [routerLink]="['/users', user.id]">{{ user.name }}</a>
<!-- Generates: /users/42 -->

<!-- Multiple params: -->
<a [routerLink]="['/posts', post.category, post.slug]">
    {{ post.title }}
</a>
<!-- Generates: /posts/angular/getting-started -->

Reading Route Params

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

@Component({
    selector: 'app-user-detail',
    template: `
        <div *ngIf="user">
            <h2>{{ user.name }}</h2>
            <p>Email: {{ user.email }}</p>
            <p>Role: {{ user.role }}</p>
        </div>
    `
})
export class UserDetailComponent implements OnInit {
    user: any;

    constructor(private route: ActivatedRoute) {}

    ngOnInit(): void {
        // Snapshot — reads the param once
        const id = this.route.snapshot.params['id'];
        console.log('User ID:', id);
        this.loadUser(id);
    }

    loadUser(id: string): void {
        // In a real app, call a service to fetch the user
        this.user = {
            id: id,
            name: 'User ' + id,
            email: `user${id}@example.com`,
            role: 'Developer'
        };
    }
}

Subscribing to Param Changes

If the component might stay mounted while the params change (e.g., "Next User" button), use the observable:

ngOnInit(): void {
    // Observable — reacts to param changes
    this.route.params.subscribe(params => {
        const id = params['id'];
        this.loadUser(id);
    });
}

Snapshot vs Observable

ApproachWhen to Use
snapshot.paramsComponent is destroyed and recreated on navigation
params.subscribe()Component stays alive and params change (e.g., same route different ID)

Practical: User List → Detail

// user-list.component.html
<div class="user-list">
    <div class="user-card" *ngFor="let user of users">
        <h3>{{ user.name }}</h3>
        <p>{{ user.email }}</p>
        <a [routerLink]="['/users', user.id]">View Profile →</a>
    </div>
</div>

Key Takeaways

  • Define params in routes with :paramName syntax
  • Link dynamically with [routerLink]="['/path', value]"
  • Read params with ActivatedRoute — inject it in the constructor
  • Use snapshot.params for one-time reads
  • Use params.subscribe() when the same component handles different params
  • Route params are always strings — convert with +id or parseInt for numbers