How to define a route with a parameter:
In your app-routing.module.ts:
const routes: Routes = [
{ path: 'product/:id', component: ProductComponent }
];
:id is a route parameter (dynamic value).
Accessing the Route Parameter in the Component
In product.component.ts:
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html'
})
export class ProductComponent {
productId!: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.productId = this.route.snapshot.paramMap.get('id')!;
// OR you can subscribe to changes:
this.route.paramMap.subscribe(params => {
this.productId = params.get('id')!;
});
}
}
Navigating to a Route with Parameters
In your template:
<a [routerLink]="['/product', 42]">View Product 42</a>
or programmatically:
this.router.navigate(['/product', 42]);
🚀 2. Query Parameters (e.g., /products?page=2&sort=price)
Adding query params to a route
In your template:
<a [routerLink]="['/products']" [queryParams]="{ page: 2, sort: 'price' }">
View Products
</a>
or programmatically:
this.router.navigate(['/products'], { queryParams: { page: 2, sort: 'price' } });
Accessing Query Parameters
In your products.component.ts:
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-products',
templateUrl: './products.component.html'
})
export class ProductsComponent {
page!: number;
sort!: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.page = Number(this.route.snapshot.queryParamMap.get('page'));
this.sort = this.route.snapshot.queryParamMap.get('sort') || '';
// OR subscribe to changes:
this.route.queryParamMap.subscribe(params => {
this.page = Number(params.get('page'));
this.sort = params.get('sort') || '';
});
}
}
✅ Quick Summary
| Feature | What it Looks Like | Accessed By |
|---|---|---|
| Route Param | /product/42 |
route.paramMap |
| Query Param | /products?page=2&sort=price |
route.queryParamMap |
Comments
Post a Comment