Defining and reading route parameters
Define the parameter in routes
app.component.ts:
const routes: Routes = [
{path: 'products/:id', component: ProductsComponent }
];
Grab the parameter using ActivatedRoute
products.ts:
import { ActivatedRoute } from '@angular/router';
export class ProductComponent {
public productId: number;
constructor(
private activatedRoute: ActivatedRoute
) {
//parameter query is returned via Observable
this.activatedRoute.params.subscribe(
params => { this.productId = params['id']; }
)
}
Send params to router links
If you want to use [routerLink]
to send parameters, here's how you do it:
an HTML template:
<!--
we assume a link for product with id = 123
the 'id' typically will be built dynamically,
inside a *ngFor statement
-->
<a [routerLink]="['/products', '123']">Product nr. 123</a>