1

I have an app whose components are structured as below:

1. Fam.Component
1.1. Header.Component <------ Unable access param from here
1.2. ParentGrid.Component
1.2.1. ChildGrid.Component
1.2.1.1 GrandChildGrid.Component <----- Can access from here!!

Clicking on an item in the parent grid, will load the child grid relevant to that item.

At the grand child level, my browser URL looks something like this:

http://onebigfamily.com/Fam/Parents/1/Children/23/GrandChildren

this will basically show all the grandchildren for the 23rd Child of the 1st parent.

the path for this URL in my routing config looks is like this:

Fam/Parents/:parentId/Children/childId:/GrandChildren

I can access the childId and parentId param values by navigating the ActivatedRoute from my GrandChildren component by doing a simple this.route.snapshot.params['childId'] (of course for parent ID have to traverse up the route tree).

Now to the question...

How can I access the :childId and :parentId from my Header Component? these values are showing up as undefined when i do a this.route.snapshot.params['childId']?

I just need to access the parent ID and the child ID as long as they are in the URL, regardless of which component has the control.

Nandun
  • 1,802
  • 2
  • 20
  • 35

3 Answers3

1

You can access child route via firstChild, so (depending on your routes config), it might look like this:

this.route.snapshot.firstChild.firstChild.params['childId']

Krzysztof Grzybek
  • 8,818
  • 2
  • 31
  • 35
0

You can get the url params in the route variable

this.route.params.subscribe(params => {
                var parentId = params['parentId'];
                var childId = params['childId'];
 });
Praveen S
  • 395
  • 4
  • 18
-1

Since you want to check route params that are different than @ your header creation time you have to subscribe to route changes and get params from change events. In your header component you have to do:

  this.route.paramMap
    .subscribe(params => {
         //assign params here
    });

where route is injected ActivatedRoute from docs

params—An Observable that contains the required and optional parameters specific to the route. Use paramMap instead.

The reason why it is not working for you is beacause your header comonent (parent) has different creation time then your child components, so route snapshot is just like that - route snapshot from the moment header is created.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99