Attributes are the most commonly used element to pass data down the component hierarchy as they are simple to use. In order to pass data down from a parent component to its child, simply use the following code:
Parent Component –
<aura:component> <aura:attribute name="parentAttribute" type="String"/> <c:childComponent childAttribute="{!v.parentAttribute}"/> </aura:component>
Child Component –
<aura:component> <aura:attribute name="childAttribute" type="String"/> </aura:component>
In this example, the parent component value of parentAttribute
is transferred to the childAttribute
of the child component via the {!v.parentAttribute}
expression.
This is perfect if you just want to display the data in a child component. What about if you also want to execute some logic when the attribute’s value changes?
Consider the following updated definition of childComponent
:
<aura:component> <aura:attribute name="childAttribute" type="String"/> <aura:handler name="change" value="{!v.childAttribute}" action="{!c.onChildAttributeChange}"/> </aura:component>
With the addition of a change handler, the child component can now trigger the onChildAttributeChange
controller function automatically when the value of childAttribute
changes. This allows us to implement some custom logic such as:
({ onChildAttributeChange : function (component, event, helper) { console.log("Old value: " + event.getParam("oldValue")); console.log("Current value: " + event.getParam("value")); } })
We now have established a top-down communication chain between the parent and the child component. This can be summarized in these few steps:
parentAttribute
value changesparentAttribute
value is transferred tochildAttribute
childComponent
’s change handler triggers theonChildAttributeChange
controller function
This approach works great for processing an attribute. What about multiple attribute changes? If you want to change two or more attributes and then trigger some logic, this method becomes unwieldy. You can either combine the attributes into a larger object (not always practical) or write a complex synchronization algorithm (please don’t). Instead, I recommend methods for multiple attribute changes
This is article from Salesforce developer blog.