Lightning components Parent-Child Communication can happen in various predefined ways
1. Using aura:attribute:
aura:attribute describes an attribute available on an app, interface, component, or event. Attribute is most commonly used communication pattern where parent component can initialize child component properties as shown below.
- First we define attribute using aura:attribute
ChildComponent.cmp
<aura:component> <aura:attribute name="firstName" type="String"/> <aura:attribute name="lastName" type="String"/> </aura:component>
2. We can set values while adding component in any parent component.
Parent Component.cmp
<aura:component> <c:ChildComponent firstName="John" lastName="Doe"/> </aura:component>
2. Using Aura:Method
Use
Above example can be modified in following way:
ChildComponent.cmp
<aura:component> <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>
ChildComponent.js
({ doAction : function(cmp, event) { var params = event.getParam('arguments'); if (params) { var param1 = params.param1; // add your code here } } }) </aura:component>
ParentComponent.cmp
<aura:component> <c:ChildComponent aura:id="compB"/> <lightning:button label="Call child method" onclick="{! c.onAction}" /> </aura:component>
ParentComponent.cmp
({ onAction : function(component, event, helper) { var objCompB = component.find('compB'); objCompB.sampleMethod("Param1", "Param2"); } })
João Lopes
-Great post!
helped me a lot when using nested components on lightning community! you literally saved me, kkkk.