Reputation: 91
How to use route parameters with ID is String?
{path: 'param/:id', component: MyComponent}
let id = this.route.snapshot.params['id'];
Blockquote
Upvotes: 3
Views: 6194
Reputation: 2937
In the component you can use this code to transform from string into number:
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap
.subscribe((params: ParamMap) => {
let id = +params.get('id'); // This line converts id from string into num
});
}
Upvotes: 1
Reputation: 2808
Using the route snapshot to get the id
query parameter as you've shown should give you a string. If you want to implicitly convert that string to a number so you can use it in a route parameter for navigation, you can prefix the variable with a +
:
// (+) converts string 'id' to a number
let id = +this.route.snapshot.params['id'];
Then:
this.router.navigate(['/example', id]);
Check out this example of getting the query param in the documentation https://angular.io/guide/router#snapshot-the-no-observable-alternative.
Upvotes: 8