I'm trying to create a lightning component ("filterPanel") that would dynamically create some child components ("customFilter")
I would like to pass the parent to children to avoid communicating with events.
I tried

     $A.createComponent('c:customFilter',{parent: this},function(){}];
    Child filter
      <aura:attribute name='parent'  type='Object'    />
      var parent = component.getReference("v.parent");

but the parent is always empty object in child context.
How can I achieve my goal?

  • you can pass the parent's attribute reference to the dynamic child component (child should have equivalent attribute to hold onto parent's attribute reference).The idea of passing this won't work.
    – Praveen
    Sep 11 '16 at 9:38
  • If you really don't want tight coupling between parent and child components.I would recommend to use component events
    – Praveen
    Sep 11 '16 at 16:49
  • I do agree with the event but it doesn't always make sense. In my case I have a dropdown and dropdown entry components. They will always be tightly coupled and communicating via events makes little sense.
    – user682217
    Sep 11 '16 at 22:45
  • Then why not pass the parent's attribute to the child component.But if really want to invoke a parent's method from child, am afraid you need to use events
    – Praveen
    Sep 12 '16 at 4:14

This is not recommended as it is kind of a hack, but you can pass a callback from the parent to the child. Locker Service does not currently prevent this from working.

You can try something like this:

Create an attribute (I used string, but other types might work) to use as the callback:

<aura:attribute aura:id="callbackattr" name='callback'  type='Object'/>

In the parent:

                   {callback: function(){
                                alert("Hi from the parent");

Then, in your child handler or controller:

var callback = component.get("v.callbackattr");
if (callback){
    callback();  //should say "Hi from the parent"

It's a bit hacky, but it's worked for me before. I actually use events now, but this is quicker, for sure.

EDIT - it still works:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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