Sunday 21 October 2018

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

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 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.

<aura:component >
    <aura:method name="GetMessageFromChildMethod" action="{!c.getMessage}"
        <aura:attribute name="Name" type="String" default="Amit"/>

Step 2) Create Child Class Controller to Get argument "event.getParam('arguments');" and return the message.

    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.

<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>

Step 4) Create Parent Component Controller to Call Aura Method "childCmp.GetMessageFromChildMethod('Amit');".

     callAuraMethod : function(component, event, helper) {
            var childCmp = component.find("childComponent");
            var retnMsg = childCmp.GetMessageFromChildMethod('Amit');
            component.set("v.message", retnMsg);
<aura:application extends="force:slds">

Output :-


Please join our YouTube Channel. Please check below related post

1Component Event in Lightning Component | aura:event  
2) Invoke Apex from Lightning Component
3) Design Resource In Lightning Component Bundle
4) Create and Destroy Modal Dialog Component

Please provide your comment and feedback.

Amit Chaudhary

Capture.JPG  @amit_sfdc    @ApexHours
  Salesforce Apex Hours