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
.
Best 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:
Then in the foo component:
And the bar component, but let's add a button to change the value when pressed:
Then in the barController:
That should update the output to be the following when the button is pressed:
If on the other hand you just did something like the following they would be independent:
And, clicking the button would result in:
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.