3

This question already has an answer here:

I came to a situation where I want to render a text based on there index value. So, Let's assume I am having a loop which is having an index variable and I want to show some specific text if the index value is 0 or 5 or 10. But I am not sure how could I use the arithmetic comparison in HTML file of LWC. Below is the sample code.

<template if:true={navigation.data} >
    <template for:each={navigation.data} for:item="tab" for:index="index">

        <!--I want to put a condition something like this-->
        <template if:true={index==0 || index==5 || index==10}>
            <p key={tab.Id}> {tab.Title__c} </p>
        </template>

        <template if:false={index==0 || index==5 || index==10}>
            <p key={tab.Id}> {tab.Title__c} </p>
        </template>

    </template>
</template>

marked as duplicate by Oleksandr Berehovskyi, Reshma, Raul, Derek F, glls Feb 15 at 13:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • @Soul_In_Code Is the series multiple of 5? – rahul gawale Feb 15 at 7:31
4

LWC is not supporting any conditional operators or expression evolution methods in markup.

To achieve this you should develop a child component and pass the data and index attributes to child component based on condition render the data in child component's markup Parent.cmp:

 <template if:true={navigation.data} >
        <template for:each={navigation.data} for:item="tab" for:index="index">

            <c-child-component index={index} data={tab}></c-child-component>

        </template>
    </template>

childComponent:

<template>
    <div>{dataToDisplay.Title__c} -- {index} --  {dataToDisplay.condition}</div>

</template>

childComponent.js:

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {
    @api index;

    @track dataToDisplay;

    @api
    get data() {
        return this.dataToDisplay
    }

    set data(value) {
        this.dataToDisplay = JSON.parse(JSON.stringify(value));

        if(this.index === 0 || this.index === 5) {
            this.dataToDisplay.condition = 'Met';

        } else {
            this.dataToDisplay.condition = 'Not Met';
        }
    }

}

Not the answer you're looking for? Browse other questions tagged or ask your own question.