Aura Method in Lightning Component | aura: method | Communicate Between Components,

In our last post we talk about Lightning Component Event for Component communication. In this post we will talk about how to do component communication with the help of <aura:method > . Aura:Method enables you to directly call a method in a component’s client-side controller instead of firing / handling a component event. With the help of  <aura:method > we can call child component method from parent component.

Syntax :-

How to call method :- Simply call the function and pass parameter value in parent component

component.sampleMethod(arg1);

How to declare method :- Declare the aura:method with attribute

<aura:method name="sampleMethod" action="{!c.callAction}" description="Sample"> 
    <aura:attribute name="param1" type="String" default="param1"/> 
</aura:method>

 

Aura Method Action :- get the Aura:Attribute value with event.getParam('arguments');
({
    callAction: function(cmp, event) {
        var params = event.getParam('arguments');
        if (params) {
            var p1 = params.param1;
            // add your code here
        }
    }
})

Get Message from Child Component to parent Component.

Step 1) Create Child component with Aura:Method.

ChildCmp.cmp

<!–ChildCmp.cmp–>
<aura:component >
<aura:method name=”GetMessageFromChildMethod” action=”{!c.getMessage}”
access=”public”>
<aura:attribute name=”Name” type=”String” default=”Amit”/>
</aura:method>
</aura:component>

Step 2) Create Child Class Controller to Get argument “event.getParam(‘arguments’);” and return the message.

ChildCmpController.js

({
getMessage : function(component, event) {
var params = event.getParam(‘arguments’);
if (params) {
var param1 = params.Name;
return “##### Hello “+param1+” From Child Component #####”;
}
return “”;
}
})

Step 3) Create a parent Component and a button to call Aura method.

ParentCmp.cmp

<!–ParentCmp.cmp–>
<aura:component >
<aura:attribute name=”message” type=”String”
default=”—— Hello From Parent —–“/>
<c:ChildCmp aura:id=”childComponent”/>

<div class=”slds-m-around_xx-large”>
<lightning:button variant=”brand” label=”Call Aura Method”
onclick=”{!c.callAuraMethod}” />
<BR></BR> <BR></BR>
<p>{!v.message}</p>
</div>
</aura:component>

Step 4) Create Parent Component Controller to Call Aura Method “childCmp.GetMessageFromChildMethod(‘Amit’);”.

ParentCmpController.js

({
callAuraMethod : function(component, event, helper) {
var childCmp = component.find(“childComponent”);
var retnMsg = childCmp.GetMessageFromChildMethod(‘Amit’);
component.set(“v.message”, retnMsg);
}
})

DemoApp.app

<aura:application extends=”force:slds”>
<c:ParentCmp/>
</aura:application>

Output :-

Write A Comment