Sub topic 3
Worked Example: A Loading, Error, and Ready Panel
Assume you know basic HTML and JavaScript, LWC templates, data binding, reactive fields, and event handlers. Conditional rendering chooses which template branch appears in the DOM.
Worked example
A component can derive its branches from one reactive status field:
<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>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';
}
}A getter is a method used like a property. The template reads its Boolean result. When status changes, LWC reevaluates the chain and renders one branch.
Nesting conditional blocks
You can place a conditional block inside another branch. Keep each inner chain valid and use getters for complex tests. Avoid deep nesting when separate child components would make the template clearer.
Migrating from if:true and if:false
The older directives test the same property twice:
<template lwc:if={isVisible}>
<p>Visible</p>
</template>
<template lwc:else>
<p>Hidden</p>
</template>Use lwc:if and lwc:else for new code. lwc:else has no value.
What happens when a branch toggles
Conditional rendering adds and removes DOM nodes. A child component in a removed branch is destroyed, so its disconnectedCallback() runs. When rendered again, a new instance is created and connectedCallback() runs. Its local state does not survive the toggle.
Removing from the DOM versus hiding with CSS
CSS hiding, such as display: none, keeps the element and child component in the DOM. The child remains mounted and keeps its state. Choose CSS hiding when quick reappearance and preserved state matter. Choose lwc:if when inactive content should be removed.
Common mistakes and how to avoid them
- Keep
lwc:elseifandlwc:elseimmediately after the preceding branch. - Do not write a value such as
lwc:else={false}. - Use a property or getter reference, not an expression such as
lwc:if={status === 'loading'}. - Remember that only the first true branch renders.
Exercise
What happens to a child component inside an lwc:if branch when the condition changes from true to false?
Show answer
The child is removed and destroyed. Its disconnectedCallback() runs, and its local state is lost.