Angular 2 v3 router - how to get the parameters of the parent route on the children's route

I have a route defined as / abc /: id / xyz

Where abc /: id allows ComponentA and / xyz is the child component displayed in the router-exit (ComponentB)

When navigating through / abc /: id / xyz, when I do this.route.params.subscribe (...) (where the route is ActivatedRoute) in ComponentA, I see: id. When I do the same in ComponentB, I do not see: id. I assume ActivatedRoute uses URL segments.

In any case, to get all the parameters on the route?

+6
source share
3 answers

Not indexed, but according to the Savkin blog, add the following to the child to get the router settings of the parent component:

constructor(activatedRoute: ActivatedRoute, router: Router) { const parentActivatedRoute = router.routerState.parent(activatedRoute); this.id = parentActivatedRoute.params.map(routeParams => routeParams.id); } 

Comparing this code with what is in the Router guide , you will need to use AsyncPipe with id in your template, or you can use subscribe() ... or you can use snapshot if you are sure that the id value will not change:

 this.id = parentActivatedRoute.snapshot.params['id']; 

@Chris mentions in a comment below: this.router.routerState.pathFromRoot(this.route) will return an array of activated routes up to the current route. Then you can get the parameters of all activated routes.

Update : RouterState.pathFromRoot(someRoute) marked deprecated in the main . In RC.5, use ActivatedRoute.pathFromRoot() .

+9
source

To keep an eye on the Mark answer , it seems like this is the method that works in the final version of Angular 2:

 constructor(route: ActivatedRoute) { let id = route.pathFromRoot[route.pathFromRoot.length - 1].snapshot.params["id"]; } 

Update: direct access to the parent route snapshot from here :

 constructor(route: ActivatedRoute) { let id = route.snapshot.parent.params['id']; } 

See also Angular 2: getting RouteParams from the parent component for other parameters.

+7
source

The parent route parameter is not passed to the child by default, but you can access them from the parent route inside the child component. @Mark Rajcok pointed you to a great post . I set out the appropriate section from this post below

  @Component({ selector: 'team', template: ` Team Id: {{id | async}} <router-outlet></router-outlet> ` }) class TeamCmp { id:Observable<string>; constructor(r: ActivatedRoute) { this.id = r.params.map(r => r.id); } } @Component({ selector: 'details', template: ` Details for Team Id: {{teamId | async}} ` }) class DetailsCmp { teamId:Observable<string>; constructor(r: ActivatedRoute, router: Router) { //get parent activated route. const teamActivatedRoute = router.routerState.parent(r); this.teamId = teamActivatedRoute.params.map(r => r.id); } } 
0
source

All Articles