4

In LWC am trying to iterate over a list and show the details from the list, this is working correctly , but as a header want to show the record number in a displayed order, below is desired outcome and simplified sample code.

Desired OutCome:

Employee Record 1:
A

Employee Record 2:
B

Employee Record 3:
C

JavaScript:

Var empNames = ["A" , "B" , "C"];

HTML:

<template for:each={empNames} for:item="employee" for:index="index">
Employee Record{index}
{employee}
</template> 

Actual outcome

Employee Record 0:
A

Employee Record 1:
B

Employee Record 2:
C

I understand as i am using {index} which indicated the position of element in an array which starts from 0 my actual outcome also starts like Employee Record 0 instead of Employee Record 1, but is there a simple way without writing much logic on JS to handle this in html and to make my headers starts from 1 instead of 0?

2 Answers 2

11

LWC does not support expression evaluation in the markup yet. I have raised an idea for it a few months back.

You have alter your JS to support complex javascript object with index of your choice.

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

    export default class App extends LightningElement {

        @api empNames = [ { name: "A" , index : 1} ,{ name: "B" , index : 2} , { name: "C" , index :3} ];
    }

Markup:

<template>
      <ul>
        <template for:each={empNames} for:item="employee" for:index="index">
             <li key={employee.index}> Employee Record {employee.index}
                {employee.name} 
             </li>
        </template> 
    </ul>
</template>

Playground Link.

8

Its not Var. Its var (case sensitive).

This is not possible because using LWC iterators you will be able to get item, index, firstItem, and lastItem. You can use either for:each or iterator:iteratorName. And in HTML you cannot do any calculations. Also getters is not possible because its inside loop. So, you have to implement in javascript only.

Its actually simple in javascript:

    this.empNames = ["A", "B", "C"];
    this.empNames = this.empNames.map((name, index) => {
        return { name, sno: index + 1 };
    });

And in HTML:

<template for:each={empNames} for:item="employee" for:index="index">
    <div key={employee.sno}>
        Employee Record{employee.sno}
        {employee.name}
    </div>
</template>
1
  • 1
    @rajasekhar, is this not solved? Commented Aug 16, 2019 at 5:06

You must log in to answer this question.

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