[SalesForce] Lightning:input in Aura:iteration values aren’t set

I am trying to create an array of String values in an lightning component using a List attribute:

<aura:attribute name="keywords" type="List" default="['','','']" />

With multiple inputs:

<aura:iteration items="{!v.keywords}" var="keyword" indexVar="i">
    <lightning:input label="Keyword" value="{!keyword}" />
</aura:iteration>

But in the controller after entering values, and invoking my handler, I get empty values?

 var keywords = component.get('v.keywords')

Am I missing something here? This appears to work in my other controllers (and I see other questions using this syntax), and seems like the appropriate setup ?

Best Answer

What's happening here is that the traditional two-way binding mechanism seems to be broken. If you put in default values (e.g. ['a','b','c']), you'll get those values instead. Or if you set it in an aura:valueInit handler (<aura:handler name="init"...), you'll see those values. I haven't heard of this happening recently, so I'll ask around. For now, though, a simple fix is to wrap the values in an object, as demonstrated here.


<aura:attribute name="keywords" type="List" default="[{value:''},{value:''},{value:''}]" />

...

<aura:iteration items="{!v.keywords}" var="item" indexVar="i">
    <lightning:input label="Keyword" value="{!item.value}" />
</aura:iteration>

...

var keywords = component.get("v.keywords").map(item => item.value);

Presuming I come up with a reason why this is not working and/or a proper response, I'll come back here an update this answer.

Related Topic