Attributes in Lightning

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  onChildAttributeChangecontroller 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:

  1. parentAttribute value changes
  2. parentAttribute value is transferred to childAttribute
  3. childComponent’s change handler triggers the onChildAttributeChange 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s