Notes
To apply a special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use the iterator directive on a template tag.
Use iteratorName to access these properties:
value—The value of the item in the list. Use this property to access the properties of the array. For example, iteratorName.value.propertyName.
index—The index of the item in the list.
first—A boolean value indicating whether this item is the first item in the list.
last—A boolean value indicating whether this item is the last item in the list.
exampleIterator.html
<template>
<lightning-card title="ExampleIterator" icon-name="custom:custom14">
<ul class="slds-m-around_medium">
<template iterator:item={contacts}>
<li key={item.value.Id}>
<div if:true={item.first} class="list-first"></div>
{item.value.Name}, {item.value.Title}
<div if:true={item.last} class="list-last"></div>
</li>
</template>
</ul>
</lightning-card>
</template>
exampleIterator.js
import { LightningElement } from 'lwc';
export default class exampleForEach extends LightningElement {
contacts = [
{
Id: 1,
Name: 'John Carter',
Title: 'Salesforce Administrator',
},
{
Id: 2,
Name: 'Will Smith',
Title: 'Salesforce Developer',
},
{
Id: 3,
Name: 'Jennifer Lopez',
Title: 'CEO',
},
];
}
exampleIterator.css
.list-first {
border-top: 1px solid black;
padding-top: 5px;
}
.list-last {
border-bottom: 1px solid black;
padding-bottom: 5px;
}