Reputation: 268
I have this in my route.ts
path: 'profile/:id',
component: ProfileComponent,
canActivate: [SiteRouteGuard],
children: [
{
path: 'albums',
component: AlbumsComponent,
canActivate: [SiteRouteGuard]
},
...
]
Now in my profile.ts I got this
localhost:4200/profile/45666
and when I route to album.ts that is chlidren of my profile.ts
localhost:4200/profile/45666/albums
Now I'm in my album.ts how can I get the id 45666?
I tried to use ActivatedRoute:
console.log(this._route.snapshot.params.id) >> undefined
Upvotes: 8
Views: 5012
Reputation: 2487
You can use the ActivatedRoute
class from angular/router
import { ActivatedRoute, Router } from "@angular/router"
public activatedRoute: ActivatedRoute
this.activatedRoute.parent.params // return observable
if you want the static value, then ask for
this.activatedRoute.parent.snapshot.params // return static values
By using the attribute parent, you can access to all the parameters and queries from the parent component
Upvotes: 13
Reputation: 71
Do it like this
import { ActivatedRoute } from "@angular/router";
let idparam = this.activatedRoute.parent.snapshot.params["idparam"]
Upvotes: 1
Reputation: 9416
Since angular 5.2.x
there is another way to access parent params.
All you have to do is set config option paramsInheritanceStrategy to 'always'
like this:
RouterModule.forRoot(routes, {
paramsInheritanceStrategy: 'always'
})
With this config, you will have access to all ancestor routes params via prototypal inheritance, so you can get it directly from activated route:
this.activatedRoute.snapshot.params
Upvotes: 16
Reputation: 544
If you are using activatedRoute you can get id in ngOnInit() method. like
this.activatedRoute.params.subscribe((params: Params) => {
var id = params['id'];
});
Upvotes: 1
Reputation: 891
You need to import ActivatedRoute from @angular/router:
import { ActivatedRoute } from "@angular/router";
Then in your constructor of AlbumsComponent you can grab that :id parameter like this:
let id = this.activatedRoute.parent.snapshot.params["id"]
Hope it helps!
Upvotes: 2