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
1 2 3 4 | < 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
1 2 3 | < 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
1 2 3 4 5 6 7 | < 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
1 2 3 4 5 6 7 8 9 10 | ({ doAction : function (cmp, event) { var params = event.getParam( 'arguments' ); if (params) { var param1 = params.param1; // add your code here } } }) </aura:component> |
ParentComponent.cmp
1 2 3 4 5 | < aura:component > < c:ChildComponent aura:id = "compB" /> < lightning:button label = "Call child method" onclick = "{! c.onAction}" /> </ aura:component > |
ParentComponent.cmp
1 2 3 4 5 6 | ({ onAction : function (component, event, helper) { var objCompB = component.find( 'compB' ); objCompB.sampleMethod( "Param1" , "Param2" ); } }) |
No comments:
Post a Comment