Sub topic 2
Rendering with the iterator directive
Assume you know basic HTML and JavaScript arrays, understand LWC templates and classes, and can use conditional rendering.
Rendering with `iterator`
The iterator:name directive repeats markup for each item in an array. The iterator name is a template variable. Each iteration exposes value, index, first, and last.
<template>
<ul>
<template iterator:contact={contacts}>
<li key={contact.value.Id}>
{contact.value.Name}
</li>
</template>
</ul>
</template>contact.value is the current object. The key must be a stable, unique identifier on the first rendered element inside the iteration.
Detecting the first and last item
Use first and last when the layout needs special markup at either boundary:
<template>
<ul>
<template iterator:contact={contacts}>
<li key={contact.value.Id}>
<span lwc:if={contact.first}>First: </span>
{contact.value.Name}
<span lwc:if={contact.last}> (last)</span>
</li>
</template>
</ul>
</template>The index property is zero-based. It is useful for display or a data-* attribute, but it is not a reliable key because positions can change when items are inserted or removed.
Choosing between `for:each` and `iterator`
Use for:each for ordinary lists. Use iterator when the template needs first, last, or the iterator index.
| Need | Directive |
|---|---|
| Render each item normally | `for:each` |
| Mark the first or last item | `iterator` |
Showing a message when the list is empty
Put the list and its fallback on opposite branches of lwc:if and lwc:else:
<template>
<ul lwc:if={hasContacts}>
<template iterator:contact={contacts}>
<li key={contact.value.Id}>{contact.value.Name}</li>
</template>
</ul>
<p lwc:else>No contacts to show.</p>
</template>Preparing display values in JavaScript
LWC templates cannot run expressions such as comparisons or method calls. Compute display values in JavaScript instead:
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
get hasContacts() {
return this.contacts.length > 0;
}
get decoratedContacts() {
return this.contacts.map((contact) => ({
...contact,
label: `${contact.Name} (${contact.Id})`
}));
}
}Bind decoratedContacts in the template when the computed label is needed.
Exercise
Which directive should you choose to label only the last item in a list?
Show answer
Use iterator, because its last property identifies the final item.