Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 get activated route parameters and parent parameters

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.

like image 952
Sathya V Avatar asked Jan 10 '17 09:01

Sathya V


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.

Can you explain the difference between ActivatedRoute and RouterState?

RouterState and ActivatedRoute are similar to their snapshot counterparts except that they expose all the values as observables, which are great for dealing with values changing over time. Any component instantiated by the router can inject its ActivatedRoute.

What is the difference between ActivatedRoute and ActivatedRouteSnapshot in Angular 4?

Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute . It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.


1 Answers

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);
    }
like image 149
Avtandil Kavrelishvili Avatar answered Oct 13 '22 03:10

Avtandil Kavrelishvili