Search code examples
angularroutesparentrouteparams

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


Solution

  • 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;
      }