I am using angular 2 to define some routes.

I've got a route setup that looks like this.

const routes: Routes = [
    { path : ':id', component : ParentComponent, 
      children : [
          { path : '', redirectTo: 'metadata', pathMatch : 'full' }
          { path : 'metadata', component : MetadataDisplayComponent },
          { path : 'data', component : DataDisplayComponent }    
      ]
    }   
]

When I try and access the "id" parameter inside ParentComponent, everything works as expected.

// ParentComponent

ngOnInit(): void {
    this.sub = this.route.params.subscribe(params => {
        this.path = params['id'];
        console.log(this.path);   // logs the value of ":id" 
    });
}

However, attempting to access that same parameter from within the child component "DataDisplayComponent" leads to an undefined result.

// DataDisplayComponent

ngOnInit(): void {
    this.sub = this.route.params.subscribe(params => {
        this.path = params['id'];
        console.log(this.path);   // logs "undefined" 
    });
}

Is there a way to cleanly grab a route parameter mapped to a parent component, while operating inside a child component? I have thought about using message passing to tell the child component, but it seems like a somewhat messy solution. Thoughts?

2

There are 2 answers

0
Zack On

I feel stupid.

I needed

this.sub = this.route.parent.params.subscribe(params => { 

This link steered me in the right location. Possible duplicate.

0
Michalis On

Since Angular 5.2.x, the router now has a new option paramsInheritanceStrategy.

You can set to the RouterModule this setting, and you will get all params from every component by simply subscribe to this.route.params.subscribe

@NgModule({
    imports: [RouterModule.forRoot(appRoutes, {
        paramsInheritanceStrategy: 'always' // THIS PARAM
    })]
})
  • This is a global configuration
  • Be careful with the same name parameters