Total Pageviews

Apex Class, Coding and Scripting, Lightning App, Lightning Component, Lightning Component Framework, Salesforce Apex, Salesforce Developer Console, Salesforce Lightning, Salesforce Lightning Application,

Lightning Aura method in Salesforce Lightning



Introduction
============

Use <aura:method> to define a method as part of a component's API. This enables you to directly call a method in a component’s client-side controller instead of firing and handling a component event. Using <aura:method>  simplifies the code needed for a parent component to call a method on a child component that it contains.
  
Example
========

Child Component:
  
  
 <aura:component>
    <aura:method name="childAuraMethod" action="{!c.getChildMessage}" access="public">
        <aura:attribute name="childParam1" type="String" default="My Blog"/>
        <aura:attribute name="childParam2" type="String" default="Name Is"/>
    </aura:method>
</aura:component>

Child Component JS Controller:
  
 ({
    getChildMessage: function(component, event) {
        //get method paramaters
        var params = event.getParam('arguments');
        if (params) {
            var param1 = params.childParam1;
            var param2 = params.childParam1;
            alert(param1 + " " + param2);
        }
    }
})
  
ParentComponent

 In the parent component, child component is added and button for calling parent component controller method.
  
<!--Parent cmp-->
<aura:component> 
    <div class="slds-m-around_xx-large">
        <!-- Add Child Component -->
        <c:ChildComponent aura:id="childCmp"/>
        <!-- On button click child aura:method will be called-->
        <lightning:button variant="brand" label="Call Child" onclick="{!c.callChilDMethod}" />
    </div>
</aura:component>

ParentComponentController

({
    callChilDMethod: function(component, event, helper) {
        //Call Child aura method
        var childComponent = component.find("childCmp");
        var message = childComponent.childAuraMethod();
    }
})
  

Using  App for testing

1
2
3
<aura:application extends="force:slds">
    <c:ParentComponent/>
</aura:application>
Happy Coding Sharing Is caring. 😀😀😀