0

I am looping through a list in LWC and want to render the field if there is a value and if there is no a value then I want to default it to a dash ( - or 0). I understand that we can conditionally render with JS by using <template if:true={}> but I can't do this because I need to pass parameters to the JS to decipher if we want to render it or not. Is it possible to do the conditional rendering in the HTML?

<tr >
    <template for:each={ml.Childs} for:item="month">
        <td class="singleBankLineItemCSS" style="text-align: center" key={month}>                 
            <lightning-formatted-number value={month.Mr.Beginning_Balance__c} format-style="currency" currency-code="USD"></lightning-formatted-number>
        </td>
    </template>
</tr>
<tr >
   <template for:each={ml.Childs} for:item="month">
       <td key={month} style="text-align: center">                                                             
           {month.Mr.Deposits_Number__c}
       </td>
   </template>
</tr>
1
  • 3
    As with all sophisticated rendering, you should move the logic out of the template and into the JavaScript. Make it so the array you iterate contains the data you will actually render.
    – Phil W
    Dec 22, 2022 at 18:50

1 Answer 1

0

Nope, this is by design.

The expression can be a JavaScript identifier (for example, person) or dot notation that accesses a property from an object (person.firstName). The engine doesn’t allow computed expressions (person[2].name['John']). To compute the value of expression, use a getter in the JavaScript class. HTML Template Directives

You will need to loop over your ml.Childs array and set the logic before rendering.

this.childrenToRender = ml.Childs.map((item) => ({
  ...item,
  // or more advanced checking here
  hasMrDepositsNumber: !item.Mr.Deposits_Number__c,
}))
<tr>
  <template for:each={childrenToRender} for:item="child">
    <td key={child}>
      <template if:true={hasMrDepositsNumber}>
        {month.Mr.Deposits_Number__c}
      </template>
    </td>
  </template>
</tr>
2
  • good idea. the only thing I am getting caught up on is that the fields are being pulled in from a query so when the returned record does not have a value for that field, the field is omitted all together. So not only is the field undefined but because it is a query we also run into object is not extensible when trying to add the field to the object.
    – Olivia
    Dec 23, 2022 at 17:59
  • So a more advanced checking is probably needed. Add a splash of Object.hasOwn() to check for the keys and you should be good.
    – lu_ke____
    Dec 24, 2022 at 10:24

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