Call Parent to Child Component Method in Lightning Aura

To call child component controller method from the parent component we can use aura:method For this, create a component as below:

<aura:component>
<aura:method name="colorCodeSaveMethod" action="{!c.colorCodeCheck}" access="PUBLIC" />
<aura:attribute name="colorName" type="String" />
<label>{!v.colorName} Color Code</label>
<ui:inputText aura:id="inputColorCode" value="" />
</aura:component>
({
colorCodeCheck : function(component, event, helper) {
var inputColorCode = component.find("inputColorCode");
var colorCode = inputColorCode.get("v.value");
if ($A.util.isEmpty(colorCode)) {
inputColorCode.set("v.errors", [{message:"Fill Color code in this field"}]);
}
}
})
The above snippet receives a color name from parent component and on pressing the save button present on the parent component will show an error if the input text is blank.

Child method out of the loop:

Simply calling the child component without any iteration will result in the code like below:
<aura:component>
<c:ChildComponent colorName="White" aura:id="colorComp"/> <br/>
<button type="button" onclick="{!c.save}">Save</button>
</aura:component>
({
save: function(component, event, helper) {
var childCmp = component.find("colorComp");
childCmp.colorCodeSaveMethod();
}
})
The above snippet will send a color name to the child component and on pressing the save button, it will call the child component controller method . The component shows an error if the input is blank.

Child method in the loop:

When we are calling child method in iteration then we can call the child component method as per below component

<aura:component>
<aura:attribute name="colorsName" type="List" default="['White','Black']" />
<aura:iteration items="{!v.colorsName}" var="colorName">
<c:ChildComponent colorName="{!colorName}" aura:id="colorComp"/>
</aura:iteration>
<button type="button" onclick="{!c.save}">Save</button>
</aura:component>
({
save: function(component, event, helper) {
var childCmp = component.find("colorComp"); // return array
for(var i = 0;i < childCmp.length;i++){
childCmp[i].colorCodeSaveMethod();
}
}
})

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

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

So, iteration is needed for the array of child component instances as well as calling their respective colorCodeSaveMethod(aura:method).


Comments