Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 v3 router - how to get parent route parameters in child route

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

Where abc/:id resolves to a ComponentA and /xyz is a child component displayed in a router-outlet (ComponentB)

When navigating to /abc/:id/xyz, when I do this.route.params.subscribe(...) (where route is an ActivatedRoute) in ComponentA i see the :id. When doing the same thing in ComponentB I do not see :id. I am guessing ActivatedRoute is using url segments.

Is there anyway to get all the parameters in the route?

like image 567
Chris Avatar asked Jul 21 '16 16:07

Chris


People also ask

How does Angular routing handle route parameters?

To access the route parameters, we use route. snapshot , which is the ActivatedRouteSnapshot that contains information about the active route at that particular moment in time. The URL that matches the route provides the productId . Angular uses the productId to display the details for each unique product.

Can you explain the difference between ActivatedRoute and RouterState?

RouterState and ActivatedRoute are similar to their snapshot counterparts except that they expose all the values as observables, which are great for dealing with values changing over time. Any component instantiated by the router can inject its ActivatedRoute.

How do I access route parameter?

The first way is through the route snapshot. The route snapshot provides the initial value of the route parameter map (called the paramMap ). You can access the parameters directly without subscribing or adding observable operators. The paramMap provides methods to handle parameter access like get , getAll , and has .


1 Answers

To follow up on Mark's answer this seems to be 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 parent route snapshot from here:

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

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

like image 150
Dan Avatar answered Oct 03 '22 22:10

Dan