How do I get the RouteParams from a parent component?
App.ts
:
@Component({
...
})
@RouteConfig([
{path: '/', component: HomeComponent, as: 'Home'},
{path: '/:username/...', component: ParentComponent, as: 'Parent'}
])
export class HomeComponent {
...
}
And then, in the ParentComponent
, I can easily get my username param and set the child routes.
Parent.ts
:
@Component({
...
})
@RouteConfig([
{ path: '/child-1', component: ChildOneComponent, as: 'ChildOne' },
{ path: '/child-2', component: ChildTwoComponent, as: 'ChildTwo' }
])
export class ParentComponent {
public username: string;
constructor(
public params: RouteParams
) {
this.username = params.get('username');
}
...
}
But then, how can I get this same 'username' parameter in those child components? Doing the same trick as above, doesn't do it. Because those params are defined at the ProfileComponent or something??
@Component({
...
})
export class ChildOneComponent {
public username: string;
constructor(
public params: RouteParams
) {
this.username = params.get('username');
// returns null
}
...
}
With RxJS's
Observable.combineLatest
, we can get something close to the idiomatic params handling:You can take component of parent route inside of child component from injector and then get any from child component. In you case like this
UPDATE:
Now that Angular2 final was officially released, the correct way to do this is the following:
ORIGINAL:
Here is how i did it using the "@angular/router": "3.0.0-alpha.6" package:
In this example the route has the following format: /parent/:id/child/:childid
In FINAL with little help of RXJS you can combine both maps (from child and parent):
Other questions one might have:
I found an ugly but working solution, by requesting the parent (precisely the 2nd ancestor) injector, and by getting the
RouteParams
from here.Something like
You can do it on the snapshot with the following, but if it changes, your
id
property will not be updated.This example also shows how you can subscribe to all ancestor parameter changes and look for the one you are interested in by merging all of the parameter observables. However, be careful with this method because there could be multiple ancestors that have the same parameter key/name.