With the help of aura method we can directly call a method in component's client side controller instead of firing and handling the component event. Basically we define aura method in child component and let parent component call the aura method of child component from its js controller which in result invoke the action written on aura method inside child component. During this parent can pass values which can be captured in child. Let's see the example below:
auraMethodDemoParent.cmp
<aura:component> <c:auraMethodDemoChild aura:id="compB"/> <lightning:button label="Call child method" onclick="{! c.onAction}" /> </aura:component>
auraMethodDemoParent.js
({ onAction : function(component, event, helper) { var objCompB = component.find('compB'); objCompB.sampleMethod("Param1 from parent", "Param2 from parent"); } })
auraMethodDemoChild.cmp
<aura:component> <!-- sampleMethod(param1, param2)--> <aura:method name="sampleMethod" action="{!c.doAction}" description="Sample method with parameters"> <aura:attribute name="param1" type="String" default="parameter 1"/> <aura:attribute name="param2" type="Object" /> </aura:method> </aura:component>
auraMethodDemoChild.js
({ doAction : function(cmp, event) { var params = event.getParam('arguments'); if (params) { var param1 = params.param1; var param2 = params.param2; alert('Received data from parent in child is '+param1+' and '+ param2); } } })
When parent component clicks on Call Child Method button, we are invoking aura method defined in child component and passing the required attributes which in result execute the onaction method written in child component where parameters passed by parent are retrieved.
Output of the above code:
For more reference please visit the below link:
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/ref_tag_method.htm
No comments:
Post a Comment