Angular2 get activated route parameters and parent parameters

Sathya V picture Sathya V · Jan 10, 2017 · Viewed 25.9k times · Source

How do I get the RouteParams from a parent component as well as child routes

export const routes: Routes = [
    { path: '', redirectTo: 'list', pathMatch: 'full' },
    { path: 'list', component: UsersComponent },
    {
        path: ':id', component: UserDetailComponent,
        children: [
            // { path: '', redirectTo: 'overview', pathMatch: 'full' },
            { path: 'overview', component: UserInfoComponent },
            { path: 'specs/:id', component: UserProfileComponent }
        ]
    }
];

In component

export class UserDetailComponent implements OnInit { 

constructor(private route: ActivatedRoute) { }
  ngOnInit() {
  this.route.parent.params.subscribe( (c) => {
        console.log(c['id']);
    });
    this.route.params.subscribe(params => {
      console.log(params['id']);
    });
}
}

But i am always getting undefined when my route is getting activated . kindly help to resolve this issue ?

Thanks in advance.

Answer

Avtandil Kavrelishvili picture Avtandil Kavrelishvili · Sep 27, 2017

Here is a simple example how to get parameter's value in .ts, After that you'll be able to customize this to your case

import { ActivatedRoute } from '@angular/router';

  constructor(private route: ActivatedRoute) {
        const taskId: string = route.snapshot.params["taskId"];
        console.log("this is taskId value = "+ taskId);
    }