Angular › Routing

How do you read a dynamic value from the URL, such as a product id, in an Angular route?

Intermediate

Answer

You define a route with a colon before a parameter name, like colon id, and inject the ActivatedRoute service to access that specific value from the current web address inside your component, either as a snapshot or as an observable that updates if the parameter changes.
{ path: 'products/:id', component: ProductDetailComponent }

constructor(private route: ActivatedRoute) {
  this.route.params.subscribe((params) => {
    console.log('Product id is', params['id']);
  });
}
Real-world example An online store shows the correct product details page for whichever product id appears in the web address, such as slash products slash 42, using the ActivatedRoute service to read that value directly.

Common follow-ups: What is the difference between reading a route parameter as a snapshot versus subscribing to it as an observable?;Can a single route have more than one dynamic parameter?