Using arithmetic comparison in if:true statement in Lightning web component

  • 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>
    

    @Soul_In_Code Is the series multiple of 5?

  • 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';
            }
        }
    
    }
    

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM