angularroutesroute-parameters

How to get :id param of child route from parent component in Angular2


I'm trying to get the :id param defined in

RouterModule.forRoot([
  {
    path: 'orders',
    component: ListComponent,
    children: [
      {
        path: 'view/:id',
        component: ViewComponent
      },
    ]
  }
])

from ListComponent.

I already tried:

route: ActivatedRoute

route.params.subscribe(params => {
  let id = +params['id'];
})

from ListComponent, but the params array is empty, I suppose it's because the :id param belongs to ViewComponent not ListComponent.

How can I get the id param in ListComponent?


Solution

  • You can use the firstChild property or the ActivatedRoute to get the child route:

    route.firstChild.snapshot.params['id']