Activity Forums Salesforce® Discussions How to call a child component"s method from its parent in Salesforce?

  • Prachi

    Member
    November 20, 2019 at 6:51 am

    Hi,

    You can take help from below link-

    https://github.com/kriasoft/react-starter-kit/issues/909

    Thanks.

  • Nikita

    Member
    November 20, 2019 at 7:13 am

    Hi Yogesh,

    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.

    For Example

    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>

     

     

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos