1

In lwc for looping through data we have

<template for:each={contacts} for:item="val">
</template>

If i have a variable where in a number is stored, say for example 4. How do i run the loop 4 times in html, inside which i'm trying to create some dynamic elements.

3

Create an array of 4 items in the JavaScript controller (that is run the loop up to the number there) and reference that much like contacts in your HTML example.

2
  • Yes i thought about that, but no other way to directly achieve it in html ? – steamyfire Jan 19 '20 at 11:19
  • 3
    Don’t think so. LWC and maybe web components in general (intentionally) try to keep expressions out of the HTML. – Keith C Jan 19 '20 at 11:23
-1

I don't think you have for: loops in LWC, however if you use child components you can sort of do what you want based on index.

Step 1. Define a child component

js

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

export default class ChildComponent extends LightningElement {
    @api index;

    get shouldDisplay() {
        return this.index <= 4;
    }
}

html

<template>
    <div if:true={shouldDisplay}>
       whatever we want here
    </div>
</template>

Step 2. Use child component in our loop in the parent component

<template for:each={contacts} for:item="val" for:index="idx">
    <c-child-component index={idx></c-child-component>
</template>

(you can also pass along your actual object etc. any other data from val obviously)

This will not stop the loop executing but the items with index > 4 won't render.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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