Reputation: 9337
I have a component that renders data retrieved from the backend. Before rendering the data needs to be filtered down based on a parameter. The last segment of the URL is a filter value, how do I pass it down into the component?
Upvotes: 0
Views: 962
Reputation: 1
you can use route params in the constructor of your component
https://angular.io/guide/router
https://angular.io/api/router/Params
constructor(routeParams: RouteParams) {
this.filter = routeParams.get('custom_filter');
}
Upvotes: 0
Reputation: 1450
First of all, if you provide us with a code example will be easier.
Now, in your app.routes.ts you should have something like this:
{
path: 'detail/:id',
component: HeroDetailComponent
}
Now you will be able tou navigate to detail/11 in this case.
In detail component you need to import this:
import { ActivatedRoute } from '@angular/router';
and add it to the constructor as private:
private route: ActivatedRoute
Then you can get the id param like this:
this.route.params.subscribe(params => {
let id = +params['id'];
this.heroService.getHero(id)
.then(hero => this.hero = hero);
});
In this case the hero id is a number. Route parameters are always strings. So we convert the route parameter value to a number with the JavaScript (+) operator. Keep that in mind.
As mentioned here, it will be better if you implements ngOnInit (subscribe to the params observable) and ngOnDestroy (destroy the sub)
Upvotes: 3