0

I have a scenario where my Lightning component needs to reference a value inside the child component of a nested component. The nesting looks like this:

- Lightning Component
  - Nested Component 1
    - Nested Component 2

The top-level Lightning component needs to get a value from Nested Component 2.

I'm familiar with getting values in a child/nested component:

var nestedCmp = component.find("nestedComponent1");
var myValue = nestedCmp.get("v.firstName");

But I don't know how to do this when the component is a child of a nested component. How can the value be referenced?

  • Have you tried events ? – codeyinthecloud Dec 12 '18 at 16:36
  • That kind of architecture can be tricky because it breaks encapsulation and couples the components tightly. One approach would be to implement methods as part of the public API of each component, each of which could source the needed value one level deeper. Knowing more about the use case might reveal further options, though. – David Reed Dec 12 '18 at 16:41
  • So which event you want to access this value on like keypress. If you can write your complete problem what you are trying to accomplish then we can help. THis might be a case of x-y problem. So please elabrote what you are trying to do – Manjot Singh Dec 12 '18 at 16:54
0

To access nested component 2, just call nestedcmp1.find("nestedcomponent2");. It has to work

  • Thank you for the suggestion. That didn't work. – Matt Smith Dec 12 '18 at 17:06
0

I really don't exactly know your use case but there are 2 use cases that i can think of.

First my outer most component is a data service and maintains state of all components. So i want to set state of my different components directly from this component. In that case we can create a facet in component.

In that case my parent component will look like-

main Component
 <c:NestedComponent1 aura:id="nestedcomp1">
    <aura:set attribute="component2">
             <c:NestedComponent2 aura:id="nestedcomp2"/>
    </aura:set>
 </c:NestedComponent1>
main component

nestedcomponent1 will be

nestedcomponent
  <aura:attribute name="component2" type="Aura.component[]"/>
   ......
    {!v.component2}
   ......
nestedcomponent

so if this is your use case then it will require design change. https://techgita.com/2018/10/02/component-facets-in-lightning-how-i-can-use-them/

Second seconior can be a event is fired from nestedcomp2 and handled at main component. In event handler you want to set some attribute in nestedcomp2. For that case we can use

eventHandler : function eventHandler(component,event){
  var source = event.getSource();
  var sourceAttribute1 = source.get('v.attribute1');
  source.set('v.attribute2','medium');
}

https://techgita.com/2018/08/30/4-awesome-tips-you-didnt-know-about-lightning-events/

Not the answer you're looking for? Browse other questions tagged or ask your own question.