We can set the routing parameter through HTML:
<a [routerLink] = "['/api/foo/', id]"/>
I know that we can read routing parameter through handling event in the typescript:
import {OnInit, OnDestroy, Component} from '@angular/core';
@Component({...})
export class MyComponent implements OnInit{
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
// subscribe to router event
this.activatedRoute.params.subscribe((params: Params) => {
let Id = params['id'];
console.log(Id);
});
}
}
However, is there any way to read route parameter in the HTML, not in the TypeScript component?
I would like to use in the following manner:
<a href="api/foo/[routerLink]"/>
if you want to get id as number. You can use this.
id:number;
ngOnInit() {
this.subscription = this.activatedRoute.params.subscribe(
(params: any) => {
if (params.hasOwnProperty('id')) {
id= +params['id'];
//do whatever you want
}
}
);
}
and this destroyed the subscription
ngOnDestroy() {
this.subscription.unsubscribe();
}
and you can access the id field on html side.
If you want to get the param in html it is better to assign the param to a variable and use it in html
private param:number;
private ngOnInit() {
// subscribe to router event
this.activatedRoute.params.subscribe((params: Params) => {
this.param = params['id'];
console.log(this.param);
});
}
in your html
<div>{{param}}</div>