How to read route parameters in Angular
Reading route parameters is essential for creating dynamic Angular applications where components need to respond to URL changes. As the creator of CoreUI with extensive Angular experience since 2014, I’ve implemented parameter-driven components in countless dashboard and admin applications. The most reliable approach is injecting ActivatedRoute service and subscribing to the params observable. This method provides real-time access to route parameters and handles parameter changes automatically.
Inject ActivatedRoute service and subscribe to the params observable to read route parameters.
import { Component, OnInit } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
@Component({
selector: 'app-user-detail',
template: '<h1>User ID: {{userId}}</h1>'
})
export class UserDetailComponent implements OnInit {
userId: string
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
this.userId = params['id']
})
}
}
This code injects the ActivatedRoute service and subscribes to the params observable in ngOnInit. When the route /user/:id is accessed, the component automatically receives the id parameter value. The subscription ensures the component responds to parameter changes if the user navigates to different user IDs without leaving the component.
Best Practice Note:
This is the same pattern we use in CoreUI Angular components for dynamic content loading. Consider using route.snapshot.params for simple cases where parameters won’t change, avoiding unnecessary subscriptions.



