Dynamic Routes with Parameters
Put a placeholder in a route to capture a value from the URL — like a product or user id.
What you will learn
- Define a route with a :parameter
- Read the parameter inside the component
- Use it to show the right item
One route, many items
You do not want a separate route for every product. Instead, use a route parameter — a placeholder marked with a colon. One route then handles /product/1, /product/2, and so on.
// app.routes.ts
import { ProductComponent } from './product.component';
export const routes = [
{ path: 'product/:id', component: ProductComponent }
];Note: Output:
(No visible output — it defines a flexible path.)
Now /product/7 matches this route, and the value 7 is captured under the name id. We read it next.
Read the parameter
Inject ActivatedRoute to read the value from the URL inside the component.
// product.component.ts
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product',
template: '<h2>Product number {{ id }}</h2>'
})
export class ProductComponent {
id: string | null = '';
constructor(private route: ActivatedRoute) {
this.id = this.route.snapshot.paramMap.get('id');
}
}Note: Output (for URL /product/7):
Product number 7
The component grabbed 7 from the URL with paramMap.get(’id’). Visit /product/42 and it shows “Product number 42”. One component, any id.
Linking with a value
Use routerLink with an array to build a link that includes the id:
<a [routerLink]="['/product', 7]">See product 7</a>Note: Output:
See product 7
Clicking it navigates to /product/7, which the dynamic route matches and renders.
Tip: Reading once with snapshot is fine when each id opens fresh. If you let users jump from product to product without leaving the page, subscribe to route.paramMap instead so the component updates each time the id changes.
Q. In the route product/:id, what does :id represent?
✍️ Practice
- Add a
user/:idroute and show “Viewing user 5” for/user/5. - Create links to three different ids using
routerLinkarrays.
🏠 Homework
- Build a list of items where each links to a detail route like
/item/:idthat displays the chosen id.