1

I have a component attribute which is as follows:

<aura:attribute name="variants" type="Map" default="{names: ['Tom', 'Dick', Harry']}" />

The array in the map is used in lightning input components as follows:

<aura:iteration items="{! v.variants.names }" var="name">
<lightning:input value="{! name }" />
</aura:iteration>

The names are displayed in the input components when they are initially rendered but I noticed that any changes made to these names in the input components are not reflected in the array. The array still has the original values. Is there a way to two-way bind the data so that changes to the names in the input components are automatically made to the Map as well?

1

That's a limitation of how two-way binding works. It's one of a class of bugs which was eliminated in LWC by removing the ability to use two-way binding. Instead, you need to be able to have a reference to an object in order to see the changes to the inputs. Here's an example I wrote that works in my developer org:

<aura:application extends="force:slds">
    <aura:attribute name="values" type="Object[]" default="[{v:'1'},{v:'2'},{v:'3'}]" />
    <aura:attribute name="outputs" type="String[]" default="['1','2','3']" />
    <aura:iteration items="{!v.values}" var="value">
        <lightning:input onchange="{!c.refresh}"  value="{!value.v}" label="Input" />
    </aura:iteration>
    <hr />
    {!join(',',v.outputs)}
</aura:application>

({
    refresh: function(component, event, helper) {
        component.set("v.outputs", component.get("v.values").map(value=>value.v));
    }
})

Here, you see that we wrap the values to edit inside objects, and we can then pull those out when changes occur. As far as I'm aware, it's always necessary to have an object when using this sort of binding if you want two-way binding to work as you expect.

|improve this answer|||||
  • So two-way binding cannot work on arrays, only objects - duly noted. I will use an onchange event as a workaround. Thanks. – user73893 Dec 25 '19 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.