Sub topic 7
Providing a fallback with lwc:else
This chapter assumes you can read an LWC template and its JavaScript class, and that you know how lwc:if shows content when a property or getter is truthy. Here you add the other half: a fallback block that renders when the condition is not met.
The problem lwc:else solves
A single lwc:if handles the "show this when" case. Many interfaces also need the opposite: show something else when the condition fails. Without a fallback you would write a second condition that mirrors the first, and the two can drift apart.
lwc:else removes that duplication. It attaches to the lwc:if directly before it. The framework evaluates the condition once and renders exactly one of the two blocks.
Basic usage
This component shows a greeting for a signed-in user and a prompt for everyone else.
<template>
<template lwc:if={isSignedIn}>
<p>Welcome back, {userName}.</p>
</template>
<template lwc:else>
<p>Please sign in to continue.</p>
</template>
</template>import { LightningElement } from 'lwc';
export default class Greeting extends LightningElement {
userName = 'Ada';
get isSignedIn() {
return Boolean(this.userName);
}
}If userName is a non-empty string, the first block renders. If it is an empty string, null, or undefined, the lwc:else block renders. The condition follows normal JavaScript truthiness, so 0, '', null, undefined, NaN, and false all select the fallback.
lwc:else takes no value
lwc:if needs a binding such as {isSignedIn}. lwc:else needs none. It means "whatever the preceding branch did not cover." Writing it with a value is a compile-time error:
<template>
<template lwc:if={isSignedIn}>
<p>Welcome back.</p>
</template>
<!-- Wrong: lwc:else does not accept an expression -->
<template lwc:else={isGuest}>
<p>Please sign in.</p>
</template>
</template>If you catch yourself wanting a condition on the fallback, you want lwc:elseif instead. That directive is covered in the next chapter.
Placing it on an element
As with lwc:if, you can put lwc:else on a <template> tag or on a regular element. Use the element form when only one element is conditional, because it avoids an extra wrapper.
<template>
<p lwc:if={hasItems}>You have {itemCount} items.</p>
<p lwc:else>Your list is empty.</p>
</template>Use the <template> form when a branch contains several sibling elements. The <template> tag itself produces no DOM node, so nothing extra appears in the rendered output.
<template>
<template lwc:if={hasItems}>
<h2>Your items</h2>
<p>{itemCount} items in your cart.</p>
</template>
<template lwc:else>
<h2>Your cart is empty</h2>
<p>Browse the catalog to add items.</p>
</template>
</template>import { LightningElement } from 'lwc';
export default class Cart extends LightningElement {
items = [];
get hasItems() {
return this.items.length > 0;
}
get itemCount() {
return this.items.length;
}
}You can mix forms in one chain. The lwc:if can be on a <template> while the lwc:else is on an element, and the reverse works too.
How the branches are chosen
The compiler links lwc:else to the block before it. At render time the engine evaluates the lwc:if expression. If it is truthy, that block renders and the lwc:else block is skipped. If it is falsy, the lwc:else block renders.
Exactly one block is in the DOM at any time. The other block does not exist, which matters for child components (a later chapter covers this).
Re-evaluation when state changes
The chain re-evaluates whenever a field or getter it depends on changes. Here a button toggles between the two blocks.
<template>
<template lwc:if={isExpanded}>
<p>{details}</p>
<button onclick={handleToggle}>Show less</button>
</template>
<template lwc:else>
<button onclick={handleToggle}>Show more</button>
</template>
</template>import { LightningElement } from 'lwc';
export default class Expander extends LightningElement {
isExpanded = false;
details = 'Here are the extra details.';
handleToggle() {
this.isExpanded = !this.isExpanded;
}
}Clicking the button flips isExpanded. The engine removes one block and inserts the other. The button in each branch is a separate DOM element, so focus and any internal state on the old button are lost when the swap happens.
Placement rules for lwc:else
The compiler enforces these rules.
| Rule | Valid | Invalid |
|---|---|---|
| Must follow an `lwc:if` or `lwc:elseif` | `lwc:if` block, then `lwc:else` block | `lwc:else` with no preceding `lwc:if` |
| Must be an adjacent sibling | Only whitespace between the blocks | Another element between the blocks |
| Takes no value | `lwc:else` | `lwc:else={flag}` |
| Appears once per chain | One `lwc:else` at the end | Two `lwc:else` blocks after one `lwc:if` |
| Goes last | `lwc:if`, `lwc:elseif`, `lwc:else` | `lwc:else` followed by `lwc:elseif` |
| One chain directive per element | `lwc:else` alone on the element | `lwc:if` and `lwc:else` on the same element |
The adjacency rule is the one that trips people up. This chain is broken because a paragraph sits between the two blocks:
<template>
<template lwc:if={isSignedIn}>
<p>Welcome back.</p>
</template>
<p>This paragraph breaks the chain.</p>
<template lwc:else>
<p>Please sign in.</p>
</template>
</template>The compiler reports an error because the lwc:else has no lwc:if directly before it. Move the paragraph above the chain or inside one of the branches.
Fallbacks with getters
Keep complex conditions in a getter so the template stays readable. The fallback then reads naturally as the negation.
<template>
<template lwc:if={canEdit}>
<lightning-button label="Edit" onclick={handleEdit}></lightning-button>
</template>
<template lwc:else>
<p>You have read-only access.</p>
</template>
</template>import { LightningElement, api } from 'lwc';
export default class RecordActions extends LightningElement {
@api isLocked = false;
@api userRole = 'viewer';
get canEdit() {
return !this.isLocked && this.userRole === 'editor';
}
handleEdit() {
this.dispatchEvent(new CustomEvent('edit'));
}
}The template cannot contain !this.isLocked && this.userRole === 'editor' directly. Template expressions accept only a property or getter reference, so the logic belongs in JavaScript. The lwc:else block covers every combination that makes canEdit false, and you do not enumerate them.
Migrating from if:false
Older templates pair if:true with if:false on the same property. Each directive is evaluated on its own, so the two blocks are not linked.
<template>
<!-- Legacy form -->
<template if:true={isVisible}>
<p>Visible</p>
</template>
<template if:false={isVisible}>
<p>Hidden</p>
</template>
<!-- Equivalent with lwc:if and lwc:else -->
<template lwc:if={isVisible}>
<p>Visible</p>
</template>
<template lwc:else>
<p>Hidden</p>
</template>
</template>The migration is mechanical. Change if:true={x} to lwc:if={x}. Delete if:false={x} and write a bare lwc:else in its place. Two things change as a result. The property is referenced once, so you cannot update one side and forget the other. The pair is also one linked chain, which lets you insert an lwc:elseif later.
Common mistakes
- Adding a value to
lwc:else. Remove it. If the fallback needs its own test, uselwc:elseif. - Separating the blocks with an element. The chain breaks. Move the element outside the chain.
- Putting
lwc:elsebefore another branch. It must be the last block in the chain. - Repeating the condition in the fallback. If you wrote
lwc:if={isOn}and a negated getter such asisOfffor the else side, deleteisOffand uselwc:else. - Expecting the fallback to render for
undefineddata. It does, becauseundefinedis falsy. Ifundefinedmeans "still loading" andfalsemeans "empty", a two-way split hides that difference. Use a three-branch chain, as the loading, error, and ready example does later.
Exercise
A template has <template lwc:if={hasAccount}>...</template>, then <p>Note: prices exclude tax.</p>, then <template lwc:else>...</template>. The compiler reports an error on the lwc:else. Why, and how do you fix it while keeping the note visible in both cases?
Show answer
The paragraph sits between the lwc:if block and the lwc:else block. lwc:else must be an adjacent sibling of the preceding lwc:if or lwc:elseif, so the paragraph breaks the chain. To fix it, move the paragraph before the lwc:if block or after the lwc:else block. Both positions keep it visible whatever the condition's value.
Exercise
Convert this legacy pair to the current directives: <template if:true={isOnline}><p>Online</p></template> and <template if:false={isOnline}><p>Offline</p></template>.
Show answer
<template lwc:if={isOnline}><p>Online</p></template><template lwc:else><p>Offline</p></template>. The lwc:else has no value and sits directly after the lwc:if block.