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.

    Some helpful SF docs on this topic (i.e. sharing bound vs. unbound attribute expressions): https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/expr_data_binding.htm

  • 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.

    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.

    Awesome! Good to know that it works for both types.

    This is from Top to bottom. Is there any way that we can set the Top most component attribute from the nested component?

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM