Expression Functions for Lightning Web Components

How can expression functions similar to Visualforce and Lightning Aura Components be achieved within lightning web components?

For example, <template if:true={index % 5 == 0}><br></template> expression index % 5 == 0 is not compyling at all.

accountList.html

<template>
    <template if:true={accounts.data}>
        <template for:each={accounts.data} for:item='item' for:index='index'>
            <!--LWC DOES NOT SUPPORT EXPRESSION FUNCTIONS-->
            <!--<template if:true={index % 5 == 0}><br></template>-->
            {item}
        </template>
    </template>
</template>

accountList.js

import {LightningElement, wire} from 'lwc';
import getAccounts from '@salesforce/apex/TestController.getAccounts';

export default class AccountList extends LightningElement {

    @wire(getAccounts) accounts;

}

Since LWC doesn’t support Expression Functions, I’d like to know how to implement them.

Answer

There are multiple options. First, note, that all computations are in JavaScript, not in the markup.

Option 1
You implement the display of your {item} (which is currently only the JSON object), into a dedicated component AccountListItem. And implement in there the logic that @POZ suggested.

Something along the lines of:

import {LightningElement, api} from 'lwc';

export default class AccountListItem extends LightningElement {
   @api index;
   @api item;

   get isMod5() {
     return this.index % 5 == 0;
   }
}

Option 2
You use a wired function instead of a wired property. And then do some fun stuff with a changed data model. Although this is hacky.

import {LightningElement, wire, track} from 'lwc';
import getAccounts from '@salesforce/apex/TestController.getAccounts';

export default class AccountList extends LightningElement {

    @wire(getAccounts)
    wiredAccounts({ error, data}) {
       if (error) {
         // do error handling, please
       } else if (data) {
         this.accounts = data.map((acct, index) => {
               return {
                  acct: acct,
                  isMod5: index % 5 == 0 ? true : false
               }
           })
       }
    }

Attribution
Source : Link , Question Author : Oleh Berehovskyi , Answer Author : codeyinthecloud

Leave a Comment