Ad
Ad
Ad
Lightning Web Components

Lightning Experience: Display tab in Lightning without overriding View button Iterate over multiple elements/Lists in Lightning Web Components using For Loop

Pinterest LinkedIn Tumblr

 

 Iterate over multiple elements/Lists in Lightning Web Components using For Loop

In this post, We will try to understand how to iterate over multiple elements in Lightning Web Components using For loop. In general, in order to iterate over a list of elements we use for loop in any programming language(C, C++,Apex) etc. Lightning web components provide us the ability to render a list of items, using for:each directive or the iterator directive to iterate over an array.

When using the for:each directive, use for:item=”currentItem” to access the current item. To assign a key to the first element in the nested template, use the key={uniqueId} directive. When a list changes, the framework uses the key to identify each item so that it can rerender only the item that changed. The key must be a string or a number, it can’t be an object. Assign unique keys to an incoming data set.

This example iterates over an array called employees, which is defined in the component’s JavaScript class.

<!– employee.html –>

<template>

    <lightning-card title=”HelloForEach” icon-name=”custom:custom14″>

        <ul class=”slds-m-around_medium”>

            <template for:each={employees} for:item=”employee”>

                <li key={employee.Id}>

                    {employee.Name}, {employee.Designation}

                </li>

            </template>

        </ul>

    </lightning-card>

</template>

// employee.js

import { LightningElement } from ‘lwc’;

export default class employee extends LightningElement {

    contacts = [

        {

            Id: 1,

            Name: ‘Marc Benioff’,

           Designation: ‘Founder & Chairman’,

        },

        {

            Id: 2,

            Name: ‘Parker Harris’,

            Designation: ‘Co-Founder’,

        },

    ];

}

Write A Comment