In this blog, I am going to show how to use aura:method .Use aura:method to communicate down the containment hierarchy. For example, a parent component calls an aura:method on a child component that it contains. aura:method 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.

Syntax 

An <aura:method> can optionally include parameters. Use an <aura:attribute> tag within an <aura:method> to declare a parameter for the method. For example:

Now you need to create a controller action to call any serverside actions with the same name as method name as shown below.Retrieve the arguments from the method using event.getParam(‘arguments’). It returns an object if there are arguments or an empty array if there are no arguments.

Server Side Controller 

Here is the below apex class which we are using in this example which will take three arguments namely sObjectName and List Of Fields to be queries and Limits for where clause.

AuraMethod.cmp

the following lightning component that contains an aura:method which contains three attributes namely sobjectName, fields, limits which will be called from the parent component.

  1. Below code is get the arguments form the aura method and set the callback functions to return the result to the parent component.

     
  2.  The below code call the server side action by passing the parameters.
  3. Below code will get the response from the server and attache it to the callback function

     

Time to Invoke aura:method

The below component is the parent component that instantiates the auraMethod.cmp . The below is the component which contains two buttons to get the accounts and contacts. On Click of lightning:button that initiates the call to the aura:method in the child component.

 

You will be able to see an output as shown below. On click of the Get Accounts Button, your parent component will call the Aura method from the child component which is used to get the data from the server side apex controller. When clicking on the contact button again your parent component will call the same child component aura method.

  1.  The below code will get the Child Component into the controller based on the aura id
  2. Below code will invoke the aura method from the child component and will return the response. After return the response we are setting the values to the attribute in parent component.