1

I have similar requirement to this How to call child component controller function/helper from Parent Component Controller the parent component has a button that will call a function from child component. For more specific, I have function that should show error messages on the individual fields while in the <aura:iteration> upon click of Save button.

ParentComponent.cmp

<aura:component>
    <aura:iteration items="{!v.listRec}" var="individualRec">
        <c:ChildComponent individualRec="{!individualRec}" aura:id="cComp"/>
    </aura:iteration>
    <button type="button" onclick="{!c.save}">Save</button>
</aura:component>

ParentController.js

({
    save: function(component, event, helper) {
        var childCmp = component.find("cComp");
        childCmp.sampleMethod();
    }
})

ChildComponent.cmp

<aura:component>
    <aura:method name="sampleMethod" action="{!c.childSave}" access="PUBLIC" />
    <aura:attribute name="individualRec" type="List" />

    <label>Email</label>
    <ui:inputText aura:id="inputEmail" value="{!v.individualRec.Email}" /
</aura:component>

ChildController.js

({
    childSave : function(component, event, helper) {
        var inputEmail = component.find("inputEmail");
        var varEmail = inputEmail.get("v.value");
        if ($A.util.isEmpty(varEmail)) {
            inputEmail.set("v.errors", [{message:"Complete this field"}]);
        }
    }
})

1 Answer 1

1

Since the child component : <c:ChildComponent aura:id="cComp"/> is inside an iteration, which means the child components generated will have the same aura:id.

As a result of that, var childCmp = component.find("cComp"); returns an Array of Child Component instance rather than one Child Component instance.

So you need iterate for the array of child component instances and call their respective sampleMethod (aura:method).

ParentController.js will look like below:

({
    save: function(component, event, helper) {
        var childCmp = component.find("cComp"); // return array
        for(var i = 0;i < childComp.length;i++){
            childCmp[i].sampleMethod();
        }
    }
})
3
  • Hi Praveen - I added this code but it throws an error "[childComp is not defined]"
    – Von
    Nov 18, 2016 at 2:33
  • Can you check your code again?. It might be a typo error: as per the answer it should be "childCmp" instead of "childComp"
    – Praveen
    Nov 18, 2016 at 4:14
  • @Von did you figure out the solution Oct 26, 2021 at 14:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .