Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access an activated child route's data from the parent route's component?

const appRoutes: Routes = [   { path: 'parent', component: parentComp, data: { foo: 'parent data' }, children: [     { path: 'child1', component: childComp1, data: { bar: 'child data 1' },     { path: 'child2', component: childComp2, data: { bar: 'child data 2' }   ]} ]; 

If I navigate to /parent/child2 and then look at the ActivatedRoute from parentComp, data.foo is defined, but data.bar is not. I have access to an array of all the children, but I don't know which one is activated.

How can I access the activated child route's data from a parent route's component?

like image 786
adamdport Avatar asked May 05 '17 13:05

adamdport


People also ask

What is an activated route?

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.


2 Answers

First child will give you access to data

constructor(route: ActivatedRoute) {   route.url.subscribe(() => {     console.log(route.snapshot.firstChild.data);    }); } 
like image 179
Julia Passynkova Avatar answered Sep 20 '22 23:09

Julia Passynkova


Working with Angular 6, I managed to get the current route data from a parent component, with the following code:

I've configured the Router with the Extra options to inherit the parent routes data:

@NgModule({   imports: [     RouterModule.forRoot(routes, {       initialNavigation: 'enabled',       paramsInheritanceStrategy: 'always'     }),   ... }) export class AppModule {} 

Then in my parent component, I was able to see the data changes with:

import { ActivatedRoute, ActivatedRouteSnapshot, NavigationEnd, Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { filter, map } from 'rxjs/operators';  subs: Array<Subscription> = [];  constructor(private router: Router, private route: ActivatedRoute) {   this.subs[0] = this.router.events     .pipe(       filter(event => event instanceof NavigationEnd),       map(() => this.route.snapshot),       map(route => {         while (route.firstChild) {           route = route.firstChild;         }         return route;       })     )     .subscribe((route: ActivatedRouteSnapshot) => {       console.log(route.data);     }); }  ngOnDestroy() {   this.subs.forEach(s => s.unsubscribe()); } 

Enjoy!

like image 24
Mateo Tibaquira Avatar answered Sep 18 '22 23:09

Mateo Tibaquira