Implement Iteration for:each directives in LWC

by Rijwan Mohmmed
implement-iteration-foreach-directives-in-lwc

Hello friends, today we will discuss Implement Iteration for:each directives in LWC. Iterate the array object or list of items in the LWC component in the HTML part we use for:each directive. It will work as for loop like we use in the JS part. An array’s first and last items can be treated differently from the iterator directive’s first and last properties.

To assign a unique ID to each item, you must use a key directive. By using the key, the framework redraws only the items that have changed when a list changes.

Also, check this: Implement Conditional Rendering If:true in LWC

Key Highlights :

  1. Iterate the list of records we use for:each directive.
  2. Use for:item=”currentItem” to access the current item
  3. To access the current item’s index, use for:index=”index”.

Process & Code :

lWCIteration.HTML :

<!-- Techdicer -->
<template>
	<lightning-card title="Implement Iteration for:each directives in LWC" icon-name="custom:custom15">
		<div class="slds-m-around_medium">
			<template for:each={data} for:item="item" for:index="index">
				<div key={item.Id}>
					<p>Index Number : {index}</p>
					<p>Name : {item.Name}</p>
					<p>Title : {item.Title}</p>
					<hr />
				</div>
			</template>
		</div>
	</lightning-card>
	<lightning-card title="Implement Iteration for:each directives in LWC" icon-name="custom:custom15">
		<div class="slds-m-around_medium">
			<template iterator:it={data}>
				<div key={it.value.Id}>
					<div if:true={it.first} class="list-first">
						First Item
					</div>
					<div if:true={it.last} class="list-last">
						Last Item
					</div>
					{it.value.Name}, {it.value.Title}<hr />
				</div>
			</template>
		</div>
	</lightning-card>
</template>

lWCIteration.JS:

import { LightningElement } from 'lwc';
export default class LWCIteration extends LightningElement {
    data = [
        {
            Id: 1,
            Name: 'Rijwan',
            Title: 'CEO',
        },
        {
            Id: 2,
            Name: 'Himanshu',
            Title: 'CTO',
        },
        {
            Id: 3,
            Name: 'Anil',
            Title: 'VP',
        },
    ];

    //@wire(fetchAccountList) data;
}

lWCIteration.js-meta.xml:

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>55.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

Output :

implement-iteration-foreach-directives-in-lwc-output techdicer.png

Reference :

  1. Render Lists

What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
3
+1
0

You may also like

Leave a Comment