15

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.

1

2 Answers 2

20

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.

3
  • 2
    Thanks a lot, Peter! This approach worked both for simple types (e.g., String) and for complex types (e.g., Account, Lead, MyCustomObject__c) in my DE org.
    – Marty C.
    Commented Nov 4, 2014 at 1:45
  • Awesome! Good to know that it works for both types. Commented Nov 4, 2014 at 12:59
  • This is from Top to bottom. Is there any way that we can set the Top most component attribute from the nested component?
    – pradeep
    Commented Sep 8, 2016 at 16:36
1

Alternatively you can use Events to pass attribute values between components if you need information from a sibling component, but don't want to fill-up your container.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .