Using aura:method to call child methods from parent methods

The aura:method command is a very useful utility that allows for defining methods in the child component API, so that a parent component can call the method directly, without having to create event files.

Let's look at the following sample code to understand the syntax.

Let's create a child component with the aura method, as follows, and name the component childMethodCmp:

<aura:method name="sampleMethod" action="{!c.doAction}" 
description="Sample method with parameters">
<aura:attribute name="param1" type="String" default="parameter 1"/>
<aura:attribute name="param2" type="Object" />
</aura:method>
/* auraMethodController.js */
({
doAction : function(cmp, event) {
var params = event.getParam('arguments');
if (params) {
var param1 = params.param1;
var param2 = params.param2
return param2;
}
},
})

Now, let's create Parent component, with the following code:

<!-- c:auraMethodCaller.cmp -->
<aura:component >
<p>Parent component calls aura:method in child component</p>
<c:childMethodCmp aura:id="child" />

<Lightning:button label="Call aura:method in child component"
onclick="{! c.callAuraMethod}" />
</aura:component>

The controller code for the parent component is shown as follows. Notice that upon the button click action, we invoke the sampleMethod method of the child component. Carefully observe how we also pass parameters to the function in the child component:

/* auraMethodCallerController.js */
({
callAuraMethod : function(component, event, helper) {
var childCmp = component.find("child");
// call the aura:method in the child component
var param = {'name' : 'Mohith'};
var auraMethodResult = childCmp.sampleMethod("1",param);
console.log("auraMethodResult: " + auraMethodResult);
},
})
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.10