How to pass values across Lightning components?

What is the best way to pass, propagate or share values across Lightning components?

For example, let’s say I have two components ns:foo and ns:bar. Both components have the following attribute:

<aura:attribute name="subject" type="String"/>

A parent component is defined as follows:

<aura:component>
    <ns:foo/>
    <ns:bar/>
</aura:component>

The behavior I want is that when v.subject is changed in ns:foo, it also changes in ns:bar.

Answer

If you pass a value that is an attribute itself on the container to the components they should share the same reference and updates to one will affect the other.

For example:

<aura:component>
    <aura:attribute name="containerSubj" default="abcd" type="String" />
    <ns:foo subject="{!v.containerSubj}"/>
    <ns:bar subject="{!v.containerSubj}"/>
</aura:component>

Then in the foo component:

<aura:component>
    <aura:attribute name="subject" type="String"/>
    <div>foo: {!v.subject}</div>
</aura:component>

And the bar component, but let’s add a button to change the value when pressed:

<aura:component>
    <aura:attribute name="subject" type="String"/>
    <div>bar: {!v.subject}</div>
    <ui:button press="{!c.changeSubject}" label="Change the Subject"/>
</aura:component>

Then in the barController:

({
    changeSubject : function(component, event, helper) {
        component.set("v.subject", "xyz");
    }
})

That should update the output to be the following when the button is pressed:

foo: xyz
bar: xyz

If on the other hand you just did something like the following they would be independent:

<aura:component>
    <aura:attribute name="containerSubj" default="abcd" type="String" />
    <ns:foo subject="abcd"/>
    <ns:bar subject="abcd"/>
</aura:component>

And, clicking the button would result in:

foo: abcd
bar: xyz

It seems to me like this approach of letting the container control it would be the way to go because it leaves the components themselves decoupled and leaves it up to the container using them to decide if it wants to implement it that way or not.

Attribution
Source : Link , Question Author : Marty C. , Answer Author : Peter Knolle

Leave a Comment