Expression in For Loop in Lightning Web Component

Expressions in Lightning Aura Component allowed us to do the calculations in the realtime and make the content more dynamic, in Lightning Web Component we have expressions but they lack a small feature that we cannot write the logic of expression in HTML component and instead, we have to write them in JS. Due to this, we are not able to pass a variable of a loop in the in Expressions

Aura

<aura:iteration items="{!v.accountList}" var="account">
	<li>
		Name : {!account.Name}<br/>
		Number Of Employees : {!account.NumberOfEmployees}<br/>
		Employees More Than 50 : {! if(account.NumberOfEmployees > 50, 'Yes','No')}<br/>
		<br/>
	</li>
</aura:iteration>

Notice the calculation we did for “Employees More Than 50”. When the iteration loops over the “accountList” then the Expression can refer to the loop element “account”. But unfortunately, it would not be possible in LWC. As the expression logic resides in JS file, it cannot refer to the loop element ‘account’.

LWC

<template for:each={accountList} for:item="account">
	<li key={account.id}>
		Name : {account.Name}<br/>
		Number Of Employees : {account.NumberOfEmployees}<br/>
		Employees More Than 50 : ???? <br/>
		<br/>
	</li>
</template>
import { LightningElement ,track, wire} from 'lwc';
import getAccountRecords from '@salesforce/apex/AccountHandler.getAccountRecords';

export default class ForLoopExpression extends LightningElement {
    @track accountList;
    @track error;
    @wire(getAccountRecords, {})   
    handleAccountRecords({ error, data }) {
        if (data) {
            this.accountList = data;
            this.error = undefined;
        } else if (error) {
            this.accountList = [];
            this.error = error;
        }
    }
}

In order to solve this, what we can do is create a new attribute in the loop element ‘account’ by first stringifying and reparsing the response from the server (so that we can set new attributes, try to set a new attribute directly and you will get an error ). We will then loop over all the elements of the list and add a new attribute which was our calculated expression in Aura.

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

export default class ForLoopExpression extends LightningElement {
    @track accountList;
    @track error;
    @wire(getAccountRecords, {})   
    handleAccountRecords({ error, data }) {
        if (data) {
            let accountList = JSON.parse(JSON.stringify(data));
            // eslint-disable-next-line guard-for-in
            for (let i in accountList) { 
                accountList[i].EmployeesMoreThan50 = ( accountList[i].NumberOfEmployees > 50 ? 'Yes':'No');
            }
            this.accountList = accountList;
            this.error = undefined;
        } else if (error) {
            this.accountList = [];
            this.error = error;
        }
    }
}

And you can access that attribute in HTML file like this

<template>
    <lightning-card title="LWC Expression in For Loop Example" >
        <div class="slds-p-horizontal_x-small">
            <template if:true={accountList}>
                <ul>
                    <template for:each={accountList} for:item="account">
                        <li key={account.id}>
                            Name : {account.Name}<br/>
                            Number Of Employees : {account.NumberOfEmployees}<br/>
                            Employees More Than 50 : {account.EmployeesMoreThan50}<br/>
                            <br/>
                        </li>
                    </template>
                </ul>
            </template>
        </div>
    </lightning-card>
</template>

in JS you are not limited to a set of limited functions provided by Aura, you can do complex calculations in expression and even use your own functions to solve those expressions as well.

Was this post useful? If yes then please share.



Leave a Comment

All fields marked with an asterisk (*) are required


shares