Sub topic 2
Providing a Fallback with `lwc:else`
This chapter assumes you know basic HTML and JavaScript, LWC templates, data binding, and reactive component fields. LWC is Lightning Web Components. Its conditional directives decide which template content exists in the DOM.
Providing a fallback with `lwc:else`
Use lwc:else after lwc:if to render alternative content when the condition is falsy. Falsy values include false, null, undefined, 0, and an empty string. Most other values are truthy.
The lwc:else directive does not take a value. It belongs to the immediately preceding conditional block.
<template>
<p lwc:if={hasItems}>You have {itemCount} items.</p>
<p lwc:else>Your list is empty.</p>
</template>When hasItems changes, LWC reevaluates the condition and adds one paragraph while removing the other. The inactive paragraph is not merely invisible. It is absent from the DOM.
Adding branches with `lwc:elseif`
Use lwc:elseif when a decision has more than two possible outcomes. LWC checks the conditions from top to bottom and renders only the first matching branch.
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<template lwc:elseif={hasError}>
<p>Something went wrong.</p>
<button onclick={handleRetry}>Retry</button>
</template>
<template lwc:else>
<p>Data is ready.</p>
</template>
</template>A getter is a JavaScript method used like a property in the template. Getters keep comparisons out of the markup.
import { LightningElement } from 'lwc';
export default class StatusPanel extends LightningElement {
status = 'loading';
get isLoading() {
return this.status === 'loading';
}
get hasError() {
return this.status === 'error';
}
handleRetry() {
this.status = 'loading';
}
}Rules for writing a valid chain
- Place
lwc:elseiforlwc:elsedirectly after its preceding conditional element or<template>. - Keep every branch at the same level.
- Give
lwc:ifandlwc:elseifa property or getter expression. - Give
lwc:elseno value. - Do not insert ordinary elements, comments, or whitespace-sensitive markup between branches.
- Nest a separate conditional block when a branch needs another decision.
Exercise
What does lwc:else render when both isLoading and hasError are false?
Show answer
It renders the ready branch because it is the fallback after all preceding conditions fail.