Reputation: 13962
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?
Upvotes: 0
Views: 537
Reputation: 6926
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
})]
})
Upvotes: 1