Sub topic 11
Nesting conditional blocks
This chapter assumes you can write a basic lwc:if, lwc:elseif, lwc:else chain and that you know how getters feed conditions in a template. It covers placing one chain inside a branch of another, how the engine evaluates nested chains, and when a flat chain is the better choice.
Why nest at all
A single chain picks one branch out of several. Sometimes a branch needs its own decision. A panel that has finished loading may still have nothing to show, so the "ready" branch has two outcomes: a list or an empty message. You can model this in two ways:
- Put a second chain inside the "ready" branch.
- Flatten everything into one chain with a more specific condition for each branch.
Both work. Nesting keeps related decisions together, and flattening keeps the template shallow. The rest of the chapter shows how to write each and how to choose.
The basic rule: a chain lives in one parent
An lwc:if chain is a set of adjacent siblings. A nested chain is a separate set of siblings placed inside one of the outer branches. The two chains never interact. An lwc:else pairs only with the nearest preceding lwc:if or lwc:elseif at its own level.
<template>
<template lwc:if={isReady}>
<template lwc:if={hasItems}>
<p>Showing your items.</p>
</template>
<template lwc:else>
<p>You have no items.</p>
</template>
</template>
<template lwc:else>
<p>Not ready yet.</p>
</template>
</template>The indentation here reflects the structure. The inner lwc:else sits inside the outer lwc:if branch and pairs with the inner lwc:if. The outer lwc:else sits one level up and pairs with the outer lwc:if. If you moved the inner lwc:else out of the outer lwc:if template, it would have no preceding lwc:if sibling to attach to, and the template would fail to compile.
How evaluation proceeds
The engine evaluates the outer chain first. It only evaluates the inner chain if the outer branch that contains it is the one selected. When the outer condition is false, the inner conditions are not consulted, and none of the inner content exists in the DOM.
The diagram below shows this for the example above.
Because the outer condition guards the inner one, you can rely on it. Inside the "ready" branch you know isReady is true, so inner getters do not need to re-check it.
A complete nested component
The next component loads a list in three stages and uses nesting for the "ready" stage. The status field drives the outer chain. The items array drives the inner chain.
<template>
<lightning-button label="Load items" onclick={handleLoad}></lightning-button>
<lightning-button label="Load nothing" onclick={handleLoadEmpty}></lightning-button>
<lightning-button label="Fail" onclick={handleFail}></lightning-button>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<template lwc:elseif={hasError}>
<p>Something went wrong.</p>
</template>
<template lwc:else>
<template lwc:if={hasItems}>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.name}</li>
</template>
</ul>
</template>
<template lwc:else>
<p>No items to show.</p>
</template>
</template>
</template>import { LightningElement } from 'lwc';
export default class ItemPanel extends LightningElement {
status = 'ready';
items = [];
get isLoading() {
return this.status === 'loading';
}
get hasError() {
return this.status === 'error';
}
get hasItems() {
return this.items.length > 0;
}
handleLoad() {
this.status = 'ready';
this.items = [
{ id: '1', name: 'Pens' },
{ id: '2', name: 'Paper' }
];
}
handleLoadEmpty() {
this.status = 'ready';
this.items = [];
}
handleFail() {
this.status = 'error';
}
}Three points about this code:
- The outer
lwc:elsecovers every status that is notloadingorerror. The inner chain therefore runs for the "ready" case and any other unexpected status value. handleLoadassigns a new array toitems. A field read by a getter triggers a re-render when it is reassigned. Callingthis.items.push(...)on a plain field would not.- The
keyattribute on thelibelongs to thefor:eachloop, not to the conditional. Conditional directives need no key.
Nesting versus flattening
The same behavior can be written as one flat chain by giving each branch a precise getter:
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<template lwc:elseif={hasError}>
<p>Something went wrong.</p>
</template>
<template lwc:elseif={isEmpty}>
<p>No items to show.</p>
</template>
<template lwc:else>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.name}</li>
</template>
</ul>
</template>
</template>get isEmpty() {
return this.items.length === 0;
}Because lwc:elseif is evaluated only after the earlier conditions failed, isEmpty is reached only when the status is neither loading nor error. That makes the flat version equivalent to the nested one here.
| Aspect | Nested chains | Flat chain |
|---|---|---|
| Template depth | Deeper, one level per decision | One level |
| Getters needed | Each getter answers one question | Getters may need to combine questions |
| Reading the logic | Grouped by parent branch | One list, read top to bottom |
| Best fit | A branch has its own independent decision | Branches are mutually exclusive outcomes of the same state |
| Risk | Misplaced `lwc:else` breaks pairing | A later branch silently depends on earlier ones failing |
A useful guideline: if the inner decision depends on different state than the outer one, nest. In the example, status and items are different pieces of state. If every branch is a different value of one field, such as status, keep the chain flat.
Keeping nesting shallow
Each nested level adds an indentation level and another pairing to track. Two levels are usually readable. Three or more tend to hide mistakes. Options when nesting grows:
- Extract the inner block into a child component and give it the data through a public property. The parent then holds only one chain.
- Turn the combinations into one
currentViewgetter that returns a string, and write a flat chain over simple getters likeisListView. - Remove branches that cannot happen. If a state is impossible, do not render a branch for it.
The second option also respects the restriction that lwc:if takes a simple property or getter reference. You cannot write lwc:if={status === 'ready' && hasItems} or lwc:if={!hasItems} in the template. Compound logic goes in a getter, whether the chain is flat or nested.
get showList() {
return this.status === 'ready' && this.items.length > 0;
}Child components inside nested branches
A child component placed in a nested branch is created only when every enclosing condition selects its branch. Its connectedCallback runs when it is inserted. When any enclosing condition changes so the branch is no longer selected, the child is removed and its disconnectedCallback runs. If the outer branch changes, a child in an inner branch is removed along with it, even if the inner condition itself did not change. When the branch returns, a new instance is created, and the old instance's internal state is gone.
<template>
<template lwc:if={isReady}>
<template lwc:if={hasItems}>
<c-item-list items={items}></c-item-list>
</template>
</template>
</template>Here c-item-list is created only when isReady and hasItems are both true. If either becomes false, the component is destroyed.
Common mistakes with nested blocks
- Misplaced
lwc:else. Anlwc:elsemust directly follow itslwc:iforlwc:elseifsibling. Check that the closing tag of the inner block ends before the innerlwc:elsebegins, and that the outerlwc:elseis not accidentally inside the outerlwc:if. - Putting a value on
lwc:else. Writelwc:elsewith no value.lwc:else={something}is invalid. - Elements between chain members. Do not put another element between an
lwc:ifand itslwc:else. The chain breaks and the template fails to compile. - Expressions in conditions. Negation, comparison, and
&&are not allowed in the directive value. Use getters. - Re-checking the parent condition in the inner getter. It is harmless but redundant, and it makes the inner getter less reusable.
Exercise
A component renders an outer chain on isSignedIn (lwc:if and lwc:else). Inside the signed-in branch, an inner chain uses hasMessages with its own lwc:else. A learner places the inner lwc:else directly after the closing tag of the outer lwc:if template, intending it to be the "no messages" message. What happens, and how do you fix it?
Show answer
The inner lwc:else is now a sibling of the outer chain. It follows the outer lwc:if template, so it pairs with isSignedIn instead of hasMessages. Together with the real outer lwc:else, that gives two lwc:else blocks in one chain, which is invalid and fails to compile. Fix it by moving the "no messages" template inside the signed-in branch, directly after the lwc:if={hasMessages} template, so that both inner blocks are siblings within the outer lwc:if template.
Exercise
Rewrite the nested example from this chapter (outer isReady chain with an inner hasItems chain) as a single flat chain. Which getter do you need to add, and why is it enough to test only the item count in it?
Show answer
Use lwc:if={isLoading}, then lwc:elseif={hasError}, then lwc:elseif={isEmpty}, then lwc:else for the list. Add get isEmpty() { return this.items.length === 0; }. Branches in a chain are tested in order, so isEmpty is only evaluated when isLoading and hasError were both false. It does not need to repeat the status checks.