Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 new Router: How to get router parameters of a child component?

In the latest version of @angular/router 3.0.0-rc.1 The way you get the parameters from a URL/route changed.

Based on this documentation you should be able to get the params by subscribing to the params but in my case it seems that is not working.

What I want to achieve is to get params into my parent component FROM child routes.

For example let's say this is my routes:

const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
    pathMatch: 'prefix',
    children: [
      {
        path: ':id',
        component: ChildComponent
      }
    ]
  }
];

I want to get the id parameter and use it in my ParentComponent. So I'm trying like this:

export class ParentComponent implements OnInit {

  sub: any;
  constructor(
    private route: ActivatedRoute) {
    this.route = route;
   }

  ngOnInit() {

    this.sub = this.route.params.subscribe(params => {
     let id = params['id'];
     console.log(id);
   });

  }

}

Like this I'm getting:

Undefined

What am I missing here?

like image 358
Vassilis Pits Avatar asked Aug 15 '16 13:08

Vassilis Pits


1 Answers

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

this.route.children

If you were in a child route and needed parameters from the parent:

this.route.parent.params

like image 113
Brandon Avatar answered Oct 11 '22 14:10

Brandon