Services & RoutingExtra· 35 min read

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.

A dynamic route: :id is a placeholder
// 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.

Read the :id value from the URL
// 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 that passes the id 7
<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?

Answer: The colon marks a route parameter — a placeholder that captures whatever value appears there in the URL, like 7 in /product/7.

✍️ Practice

  1. Add a user/:id route and show “Viewing user 5” for /user/5.
  2. Create links to three different ids using routerLink arrays.

🏠 Homework

  1. Build a list of items where each links to a detail route like /item/:id that displays the chosen id.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →