3

I tried to create an input component as follows:

<aura:attribute name="dataTotal" type="Map" />
<aura:attribute name="myBoolean" type="Boolean" />

<lightning:input type="number" value="{! if(v.myBoolean, v.dataTotal.length, v.dataTotal.precision) }" required="true" />

However, I noticed that the input of the component was not being saved into dataTotal as expected and I think the expression in the value property of the component is responsible. Is such a conditional assignment of the value not possible or is my syntax wrong? If the former, do I have to separate out the code as such:

<aura:if isTrue="{! v.myBoolean }">
    <lightning:input type="number" value="{! v.dataTotal.length }" required="true" />
<aura:set attribute="else">
     <lightning:input type="number" value="{! v.dataTotal.precision }" required="true" />
</aura:set>
</aura:if>

1 Answer 1

1

Expressions which must be evaluated (such as using the if expression in your first example) do not work with two-way binding. As such, you will need need to either (a) bind the value in aura:if (as in your second example), or (b) set the reference dynamically. For example, you could conceptually do this:

<aura:attribute name="myBoolean" type="Boolean" default="true" />
<aura:attribute name="dataTotal" type="Map" default="{length:0, precision:2}" />
<aura:handler name="init" value="{!this}" action="{!c.update}" />
<aura:handler name="change" value="{!v.myBoolean}" action="{!c.update}" />

<lightning:input aura:id="myInput" label="My Input" />

...

update: function(component, event, helper) {
    let myBoolean = component.get("v.myBoolean");
    let fieldToUpdate = component.getReference("v.dataTotal."+(myBoolean?'length':'precision'));
    let input = component.find("myInput");
    input.set("v.value", fieldToUpdate);
}

Using getReference gives you a two-way binding. This should work for most ordinary scenarios.

1
  • It seems that two-way binding as it is currently implemented has a number of limitations and caveats on which I have tripped up severally. I wish Salesforce would produce some documentation on this as two-way binding is a critical element of any lightning component development work.
    – user73893
    Dec 25, 2019 at 6:54

You must log in to answer this question.

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