0

I have two numeric values that I want to add together and be outputted by a lightning:formattedNumber component. I can give pass either value individually to the component and it renders, but not when I attempt to add these together.

Here is the syntax I'm using, but it renders nothing:

{!myAttr.value1 + myAttr.value2}

Example:

<aura:iteration items="{!v.myControlWrapper}" var="myAttr" indexVar="ind"> 
    ...
        <lightning:formattedNumber value="{!myAttr.value1 + myAttr.value2}" style="currency" currencyCode="USD" />
3
  • 1
    Have you tried the alternative syntax? {!add(myAttr.value1,myAttr.value2)} Do you get any errors on the F12 Developer Console?
    – sfdcfox
    Nov 2, 2021 at 18:11
  • @sfdcfox I just tried your suggestion but it also didn't render a value. There don't appear to be any errors in the console.
    – Matt Smith
    Nov 2, 2021 at 18:23
  • I read about a similar issue with math expressions and I was able to do this by multiplying the value of value1 and value2 by 1. Ex: {!(myAttr.value1 * 1) + (myAttr.value2 * 1)}, as well as {!add(myAttr.value1 * 1,myAttr.value2 * 1)}
    – Matt Smith
    Nov 3, 2021 at 12:49

1 Answer 1

0

Without more context, it's hard to tell, but you do need to make sure that your attributes are actually numbers, and that the data is mapped correctly. Here's a copy-paste example you can use; this might help you debug the problem.

<aura:application >
    <aura:attribute name="rows" type="List" default="[]" />
    <aura:iteration items="{!v.rows}" var="row" indexVar="rowindex">
        <div data-row="{!rowindex}" class="demo">
        <lightning:input name="value1" onchange="{!c.update}" step="0.01" label="Value1" type="number" value="{!row.value1}" />
        <lightning:input name="value2" onchange="{!c.update}" step="0.01" label="Value2" type="number" value="{!row.value2}" />
        <lightning:formattedNumber value="{!row.value1 + row.value2}" style="currency" currencyCode="USD"/>
        </div>
    </aura:iteration>
    <lightning:button label="Add row" onclick="{!c.add}" />
</aura:application>

({
    update: function(component, event, helper) {
        let rows = component.get("v.rows");
        debugger;
        let index = event.target.closest('div[data-row]').dataset.row;
        let field = event.target.name;
        rows[index][field] = event.target.value;
        rows[index].value1 = parseFloat(rows[index].value1);
        rows[index].value2 = parseFloat(rows[index].value2);
        component.set("v.rows", [...rows]);
    },
    add: function(component, event, helper) {
        let rows = [...component.get("v.rows"), {value1: 0, value2: 0}];
        component.set("v.rows", rows);
    }
})

You must log in to answer this question.

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