How to Get Route Params in Angular: Simple Guide
In Angular, you get route parameters using the
ActivatedRoute service. You can access them synchronously with snapshot.paramMap.get('paramName') or reactively by subscribing to paramMap observable to handle changes.Syntax
Use ActivatedRoute to access route parameters. You can get a parameter by name using paramMap.get('paramName'). For dynamic updates, subscribe to paramMap observable.
this.route.snapshot.paramMap.get('id'): gets the parameter once.this.route.paramMap.subscribe(params => ...): listens for parameter changes.
typescript
constructor(private route: ActivatedRoute) {} // To get param once const id = this.route.snapshot.paramMap.get('id'); // To react to param changes this.route.paramMap.subscribe(params => { const id = params.get('id'); // use id });
Example
This example shows a component that reads the id parameter from the route and displays it. It updates if the parameter changes while the component is active.
typescript
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-user-detail', template: `<p>User ID: {{ userId }}</p>` }) export class UserDetailComponent implements OnInit { userId: string | null = null; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.paramMap.subscribe(params => { this.userId = params.get('id'); }); } }
Output
User ID: 42
Common Pitfalls
1. Using snapshot only when parameters can change without recreating the component will cause stale data.
2. Forgetting to subscribe to paramMap means you miss updates if the route changes while the component is active.
3. Accessing parameters directly from route.params without using paramMap is less safe and not recommended.
typescript
/* Wrong: Using snapshot only when params can change */ ngOnInit() { const id = this.route.snapshot.paramMap.get('id'); // If route param changes, id won't update } /* Right: Subscribe to paramMap for updates */ ngOnInit() { this.route.paramMap.subscribe(params => { const id = params.get('id'); // id updates on param change }); }
Quick Reference
this.route.snapshot.paramMap.get('paramName'): Get param once.this.route.paramMap.subscribe(params => ...): React to param changes.- Always inject
ActivatedRoutein constructor. - Use
paramMapoverparamsfor safer access.
Key Takeaways
Use ActivatedRoute's paramMap to access route parameters safely.
Subscribe to paramMap to handle parameter changes dynamically.
Avoid relying only on snapshot if parameters can change without component reload.
Always inject ActivatedRoute in your component constructor.
Prefer paramMap over params for better API consistency and safety.