In lwc for looping through data we have

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

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.


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.

  • 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

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


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

export default class ChildComponent extends LightningElement {
    @api index;

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


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

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>

(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.