To iterate over list we can use two directives
- for:each
- Iterator
Whenever we use for:each or Iterator we need to use key directive on the element on which we are doing iteration. Key gives unique id to each item. Remember, without key we cannot do iteration.
When a list changes, the framework uses the key to rerender only the item that changed. It is used for performance optimization and isn’t reflected in the DOM at run time.
for:each
- 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.
- you can use them for:index=”index” to access the current item index, it is optional
Example
HelloForEach.html
<template>
<lightning-card title="HelloForEach" icon-name="custom:custom14">
<ul class="slds-m-around_medium">
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>
{contact.Name}, {contact.Title}
</li>
</template>
</ul>
</lightning-card>
</template>
HelloForEach.js
import { LightningElement } from 'lwc';
export default class HelloForEach extends LightningElement {
contacts = [
{
Id: 1,
Name: 'Amy Taylor',
Title: 'VP of Engineering',
},
{
Id: 2,
Name: 'Michael Jones',
Title: 'VP of Sales',
},
{
Id: 3,
Name: 'Jennifer Wu',
Title: 'CEO',
},
];
}
Output:
Another Practical Example:
iterator
If you want add 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.
Sample Example:
HelloIterator.html
<template>
<lightning-card title="HelloIterator" icon-name="custom:custom14">
<ul class="slds-m-around_medium">
<template iterator:it={contacts}>
<li key={it.value.Id}>
<div if:true={it.first} class="list-first"></div>
{it.value.Name}, {it.value.Title}
<div if:true={it.last} class="list-last"></div>
</li>
</template>
</ul>
</lightning-card>
</template>
helloIterator.css
.list-first {
border-top: 1px solid black;
padding-top: 5px;
}
.list-last {
border-bottom: 1px solid black;
padding-bottom: 5px;
}
No comments:
Post a Comment