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>
.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',
},
];
}
OUTPUT
Iterator directive:
If you have the requirement to access the first and the last element in the list use the iterator directive.
.html file
.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>
.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',
},
];
}
OUTPUT
No comments:
Post a Comment