We use cookies to enhance your experience on the site
CodeWorlds

Route Parameters

Reading Parameters

1import { Component, inject, OnInit } from '@angular/core';
2import { ActivatedRoute, ParamMap } from '@angular/router';
3
4@Component({
5  selector: 'app-samurai-detail',
6  standalone: true,
7  template: \`
8    <h1>Samurai #{{ samuraiId }}</h1>
9    <p>Sort order: {{ sortOrder }}</p>
10  \`
11})
12export class SamuraiDetailComponent implements OnInit {
13  private route = inject(ActivatedRoute);
14
15  samuraiId = '';
16  sortOrder = '';
17
18  ngOnInit(): void {
19    // Method 1: Snapshot (for static parameters)
20    this.samuraiId = this.route.snapshot.paramMap.get('id') ?? '';
21    this.sortOrder = this.route.snapshot.queryParamMap.get('sort') ?? 'default';
22
23    // Method 2: Observable (for dynamic changes)
24    this.route.paramMap.subscribe((params: ParamMap) => {
25      this.samuraiId = params.get('id') ?? '';
26    });
27
28    this.route.queryParamMap.subscribe(params => {
29      this.sortOrder = params.get('sort') ?? 'default';
30    });
31  }
32}

Programmatic Navigation

1import { Router } from '@angular/router';
2
3@Component({...})
4export class NavigationComponent {
5  private router = inject(Router);
6
7  goToSamurai(id: number): void {
8    // Absolute navigation
9    this.router.navigate(['/samurai', id]);
10
11    // With query params
12    this.router.navigate(['/samurai'], {
13      queryParams: { sort: 'name', order: 'asc' }
14    });
15
16    // Preserve query params
17    this.router.navigate(['/samurai', id], {
18      queryParamsHandling: 'preserve'
19    });
20
21    // Navigation by URL
22    this.router.navigateByUrl('/samurai/123?sort=level');
23  }
24}
Go to CodeWorlds