Sub topic 12
Nesting one list inside another
This chapter assumes you can render a flat list with for:each, you know why each item needs a key, and you can use lwc:if and lwc:else. Here you will render a list inside a list, such as accounts that each contain contacts.
The shape of nested data
A nested list starts with nested data. Each outer item holds an array of inner items.
// accountTree.js
import { LightningElement } from 'lwc';
export default class AccountTree extends LightningElement {
selected;
accounts = [
{
Id: '001A',
Name: 'Acme',
contacts: [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
]
},
{ Id: '001B', Name: 'Globex', contacts: [] }
];
get decoratedAccounts() {
return this.accounts.map((account) => ({
...account,
hasContacts: account.contacts.length > 0
}));
}
handleSelect(event) {
const { accountId, contactId } = event.currentTarget.dataset;
this.selected = `${accountId}/${contactId}`;
}
}The template cannot evaluate account.contacts.length > 0. The getter decoratedAccounts computes hasContacts once per account, the same technique you used for per-item display values.
Writing the nested template
Put the inner for:each inside the element that carries the outer key. Give each loop its own for:item name. If both loops used item, the inner name would hide the outer one and you could not read the account from inside the contact loop.
<!-- accountTree.html -->
<template>
<ul>
<template for:each={decoratedAccounts} for:item="account">
<li key={account.Id}>
{account.Name}
<ul lwc:if={account.hasContacts}>
<template for:each={account.contacts} for:item="contact">
<li key={contact.Id}
data-account-id={account.Id}
data-contact-id={contact.Id}
onclick={handleSelect}>
{contact.Name}
</li>
</template>
</ul>
<p lwc:else>No contacts for this account.</p>
</li>
</template>
</ul>
</template>Three details matter here:
- Each
<template for:each>needs its own key, set on the first element directly inside it. The outer key is on the outerli, and the inner key is on the innerli. - Inside the inner loop,
{account.Id}still works because the outer item is in scope. That is how the click handler gets both identifiers. - The empty-list fallback applies per account. Globex has no contacts, so it shows the message while Acme shows its list.
Keys in nested loops
A key only has to be unique among its siblings. Two different accounts may each have a contact with the same position or even the same Id, and LWC will not complain, because those li elements sit in different parents. In practice, real record Ids are unique anyway, so use them at both levels.
Do not build inner keys from the position in the array. The same reasons apply as for flat lists: if items are inserted or removed, index-based keys cause elements to be reused for the wrong data.
Updating nested data
When you change an inner array, replace the arrays along the path to the change. This keeps the update visible to the template, as it does for a flat list.
addContact(accountId, contact) {
this.accounts = this.accounts.map((account) =>
account.Id === accountId
? { ...account, contacts: [...account.contacts, contact] }
: account
);
}The outer array is new, the changed account is a new object, and its contacts array is new. Accounts that did not change are reused as they are.
Keeping nesting manageable
Each level of nesting adds more template and more getters. Two levels are usually fine. If you need three or more, or the inner list needs its own events and state, move the inner list into a child component and pass the array to it through a public property. The child then has a flat list to render, and its key logic stays simple.
Exercise
In the nested template, the inner loop reads {account.Id} to fill data-account-id. Why does this work, and what would break if both loops used for:item="item"?
Show answer
The outer item stays in scope inside the inner loop, so account is readable there. If both loops used item, the inner item would hide the outer one, so the inner template could only read the contact and could not reach the account's Id.