35. Accessing Route Parameters
Dynamic routes require parameters (e.g., /user/10, where 10 is the parameter). Angular provides the ActivatedRoute service to access these parameters.
1. Defining a Parametrized Route
Use a colon (:) followed by the parameter name.
typescript const routes: Routes = [ { path: 'user/:id', component: UserDetailComponent } ];
2. Accessing Parameters: Snapshot (Static Data)
If the component is guaranteed to be destroyed and recreated whenever the route changes (e.g., navigating from /user/1 to /about), the snapshot is sufficient.
typescript import { ActivatedRoute } from '@angular/router';
export class UserDetailComponent implements OnInit { userId: string | null = null;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void { // Reads the parameter instantly upon initialization this.userId = this.route.snapshot.paramMap.get('id'); // Fetch user data using this.userId } }
3. Accessing Parameters: Observable (Reactive Data)
If the user navigates between routes that use the same component (e.g., /user/1 to /user/2), the component instance is reused, and ngOnInit does not fire again. In this case, we must subscribe to the paramMap Observable to react to changes.
typescript // ... in UserDetailComponent
ngOnInit(): void { this.route.paramMap.subscribe(params => { this.userId = params.get('id'); console.log('New User ID:', this.userId); // Re-fetch data here every time the ID changes }); }
Best Practice: Always use the Observable approach for route parameters unless you are certain the component will never navigate to itself.