Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 711
Fernando Popoca Ortiz Avatar asked Jan 09 '17 17:01

Fernando Popoca Ortiz


People also ask

What is ActivatedRoute firstChild?

The ActivatedRoute has getters to access its parent/child route information. In order to access the first child route from the parent, you would use: this.route.firstChild.params. If you wanted all the child routes you would use the children property. This returns an array of ActivatedRoute.

Which property is used to define child routes within a route object?

You can create a nested routing by defining child routes using the children property of a route (alongside a path and component properties). You also need to add a nested router-outlet in the HTML template related to the component linked to the parent route (In our case it's the admin route).

Where would you define child URL routes in angular?

In Angular, the router lets you add child routes using the children property inside the routing module. Here you can see that the routing module has been updated with the child route and added to the array of components so we do not need to import all of them wherever we go.

What is ActivatedRoute?

The ActivatedRoute is the API that holds observable data that you can use to react to events with. You can subscribe to specific observable properties to get data from it asynchronously. The ActivatedRoute also contains ActivatedRouteSnapshot.


1 Answers

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

route.firstChild.snapshot.params['id'] 
like image 81
Günter Zöchbauer Avatar answered Sep 29 '22 11:09

Günter Zöchbauer