Salesforce Cookies #7

Untitled

Calling a child lightning component method from the parent lightning component

When we have multiple nested components then we may run into a scenario in which our parent lightning component is supposed to call a method of its child component. This is a very common use case.


simplifies the code needed for a parent component to call a method on a child component that it contains

The lightning component framework has  which simplifies the code needed for a parent component to call a method on a child component that it contains. Following example states pretty everything you want to know about it.

Declare the method defination and it’s parameters in child component as explained below.

<aura:method name="handleShowHidePopupEvent" action="     {!c.handleShowHidePopupEventAction}"      description="Method to show or hide the popup from a button on the parent      component">
    <aura:attribute name="showPopup" type="Boolean" default="true"/>
</aura:method>

Create a handler method in the client side controller of the same child component

({
   handleShowHidePopupEventAction : function(cmp, event) {
     var params = event.getParam('arguments');
     if (params) {
       var showPopup = params.showPopup;
       if(showPopup) {
         var cmpTarget = cmp.find('popupParentDiv');
         $A.util.removeClass(cmpTarget, 'slds-hide');
       } else {
         var cmpTarget = cmp.find('popupParentDiv');
         $A.util.addClass(cmpTarget, 'slds-hide');
       }
     }
   }
})

Above code snippet is toggling a parent div of the popup (model). You can also write any specific logic here which you just want to have in the child component only.

Calling method from the parent component – To close the popup after executing the save button logic or cancel button logic

<c:editRecordComponent aura:id="editRecordCmp"/>
<button class="slds-button" type="button" onclick="{!c.saveRecord}"> Save & Close </button>
<button class="slds-button" type="button" onclick="{!c.cancel}"> Cancel </button></pre>

Method in parent component controller

({
  cancel : function(cmp, helper, event){

    var editRecordCmp = component.find("editRecordCmp");
    editRecordCmp.handleShowHidePopupEvent( false );
  }
})

can also return a value once the execution has been completed.

To read more about, please check aura:method in Lightning Components Developer Guide.

Happy coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s