Loading

Quipoin Menu

Learn • Practice • Grow

angular / Route Parameters
tutorial

Route Parameters

Imagine an e-commerce site with thousands of products. You can't create a separate route for every product. Instead, you need a pattern like /product/123, /product/456. This is where route parameters come in – they let you capture dynamic values from the URL.

Defining Route with Parameters
Use a colon (:) followed by a parameter name in the path:


const routes: Routes = [
{ path: 'product/:id', component: ProductDetailComponent },
{ path: 'user/:userId/post/:postId', component: UserPostComponent }
];

Accessing Route Parameters
In your component, inject the ActivatedRoute service to access parameters.

Method 1: Snapshot (for one-time read)


import { ActivatedRoute } from '@angular/router';

@Component({...})
export class ProductDetailComponent {
productId: number;

constructor(private route: ActivatedRoute) {
// Get parameter once
this.productId = this.route.snapshot.paramMap.get('id');
console.log('Product ID:', this.productId);
}
}

Method 2: Observable (for dynamic updates)
If the component can be reused without destroying (like navigating from product 123 to product 456), use the observable approach:


export class ProductDetailComponent implements OnInit {
productId: number;

constructor(private route: ActivatedRoute) { }

ngOnInit() {
this.route.paramMap.subscribe(params => {
this.productId = +params.get('id'); // + converts to number
this.loadProduct(this.productId);
});
}
}

Query Parameters
For optional parameters like /products?category=electronics&sort=asc:


// Access query params
this.route.queryParams.subscribe(params => {
const category = params['category'];
const sort = params['sort'];
});

// Navigation with query params
this.router.navigate(['/products'], {
queryParams: { category: 'electronics', sort: 'asc' }
});
Two Minute Drill
  • Route parameters capture dynamic URL values.
  • Define with colon syntax: `path: 'product/:id'`.
  • Use ActivatedRoute to access parameters.
  • Snapshot for one-time read, paramMap observable for dynamic updates.
  • Query parameters handle optional key-value pairs.

Need more clarification?

Drop us an email at career@quipoinfotech.com