Ross Grambo
Ross Grambo

Reputation: 157

Angular 2 Routing: Parent Handling Parameter

I'm running into an error with my Angular 2 Routing. (Using angular/router2.0.0-rc1)

Heres what the routes look like:

tabs/editItem (For creating a new item)
tabs/id/editItem (For editing an item)
tabs/id/itemStuff
tabs/id/differentStuff

On my tabs component, I need to disable the itemStuff and differentStuff options when no ID is given, but enable when there is an id.

I used NgIf on the ID in my template and:

  routerOnActivate(curr: RouteSegment) {
    if(curr.getParam('pId') == null)
      return;

    this.pId = +curr.getParam('pId');
  }

The problem is that I cannot access the routes parameters from my Tabs page because "routerOnActivate" is only called at the routes endpoint. It appears an option is to have the children elements do the check for me and then send an event back for the Tabs component to update, but that seems ugly and not the right way to do this.

Any help is appreciated!

TLDR: How can a parent component access and handle a parameter

Upvotes: 1

Views: 817

Answers (2)

rrfenton
rrfenton

Reputation: 26

Resurrecting this since I just ran into this issue. You should be able to grab properties from the parent by climbing up the ActivatedRoute tree.

  getId(route: ActivatedRouteSnapshot){
      let id = route.params["id"];
      if(id)
      {
        return id;
      }
      if(route.parent)
      {
        return this.getId(route.parent)
      }
      return undefined;
  }

Upvotes: 1

Ian
Ian

Reputation: 5883

Firstly, its likely best that you upgrade your project so that you're using v3 of the router. The v2 router is no longer being developed and the v3 router works quite differently to the v2 router.

As for your parent/child parameter issue, unfortunately you'll have a bit of the same problem of v3 in that children routes are not given the parents parameters. They are delivered via a new injectable router component ActivatedRoute which only holds the parameters for the given route, not its parent or children.

This behaviour appears to be by design which means that you will need to handle parameters in the components that 'own' that parameter, and then make these available via a seperate service to your other parent / child routes.

As for a workaround, I haven't yet seen any ways of doing this directly through the routers components, but I'd say that with the constant changes to the routers API, workarounds are likely not a stable option regardless.

I guess that while this seems like this behaviour might be the wrong way of doing things and more difficult, its a strong separation of concerns which on larger projects is going to make your project more robust in the long run.

Hope this helps!

Upvotes: 1

Related Questions