Monday, December 30, 2019

for:each directive and iterator directive in lightning web component

for:each directive:

for:each directive is used to render an array. To render an array add the for:each directive to a nested template tag, for:item is used to access the current item, for:index is used to access the current index.

.html file

<template>
    <template for:each={students} for:item="item" for:index="index">
        <p key={item.id}>
            {item.Name}
            {item.Branch}
        </p>
    </template>
    
</template>

for:each loop in lightning web component


.js file

import { LightningElement } from 'lwc';

export default class HelloForEach extends LightningElement {
    students = [
        {
            Id: '112',
            Name: 'Farukh',
            Branch: 'CS',
        },
        {
            Id: '113',
            Name: 'Haider',
            Branch: 'CS',
        },
        {
            Id: '114',
            Name: 'Shaikh',
            Branch: 'IT',
        },
    ];
}

for each in lwc

OUTPUT

for:each directive and iterator directive in lightning web component

Iterator directive:


If you have the requirement to access the first and the last element in the list use the iterator directive.

.html file

<template>
    <!--for:each-->
    <b>for:each directive</b>
    <template for:each={students} for:item="item" for:index="index">
        <p key={item.id}>
            {item.Name}
            {item.Branch}
        </p>
    </template>
    <!--Iterator directive-->
    <b>Iterator directive</b>
    <template iterator:it={students}>
<li key={it.value.id}>
{it.value.id}
{it.value.Name}
{it.value.Branch}
</li>
<!--To access the first and the last element use {it.first} and {it.last}-->
    </template>
   
</template>

for:each directive and iterator directive in lightning web component


.js file

import { LightningElement } from 'lwc';

export default class HelloForEach extends LightningElement {
    students = [
        {
            Id: '112',
            Name: 'Farukh',
            Branch: 'CS',
        },
        {
            Id: '113',
            Name: 'Haider',
            Branch: 'CS',
        },
        {
            Id: '114',
            Name: 'Shaikh',
            Branch: 'IT',
        },
    ];

}

for:each directive and iterator directive in lightning web component

OUTPUT

for:each directive and iterator directive in lightning web component

No comments:

Post a Comment