Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Angular parent route data from children

I'd like to have the same data in children routes, but I can't find a way for accessing the parent route's data. That is, now I have:

{ path: 'parent-path', component: parentComponent, children: [
    { path: 'child1', component: child1Component,
      data: { sharedData: 'sharedData', child1Data: 'child1Data' }},
    { path: 'child2', component: child2Component,
      data: { sharedData: 'sharedData', child2Data: 'child2Data' }},
    { path: 'child3', component: child3Component,
      data: { sharedData: 'sharedData', child3Data: 'child3Data' }}          
]}

What I want is not have to repeat the same sharedData in all children. I tried this:

{ path: 'parent-path', data: { sharedData: 'sharedData'}, component: 
  parentComponent, children: [
    { path: 'child1', component: child1Component,
      data: { child1Data: 'child1Data' }},
    { path: 'child2', component: child2Component,
      data: { child2Data: 'child2Data' }},
    { path: 'child3', component: child3Component,
      data: { child3Data: 'child3Data' }}          
]}

But, by this way, in each component I only have his own data (childXData).

How could I access the parent route's data from the children?

like image 959
scmoure Avatar asked Jul 29 '26 00:07

scmoure


1 Answers

In child you can inject ActivatedRoute (route: ActivatedRoute) and then you can do: route.parent.snapshot.data['sharedData'] or without snapshot if you need observable.

like image 183
jbojcic Avatar answered Jul 31 '26 16:07

jbojcic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!