Sub topic 6
Showing and hiding content with lwc:if
This chapter assumes you can create a Lightning Web Component bundle, and that you know how {property} binding and getters work in a component class. Here you will use a getter to decide which part of a template is rendered.
The conditional directives
LWC templates cannot evaluate expressions such as {items.length > 0}. A condition must be a property or a getter. Three directives work together on a <template> tag:
lwc:if={condition}renders its block when the value is truthy.lwc:elseif={condition}is checked only if the earlier branches were falsy.lwc:elserenders when no earlier branch matched. It takes no value.
The directives are put on a <template> element, which adds nothing to the DOM. The content inside appears only when its branch is chosen. When a branch is not chosen, its elements are removed from the DOM, not just hidden.
A worked example
This cart shows a message that depends on whether the array has items. The template contains only a reference to hasItems.
<!-- cart.html -->
<template>
<template lwc:if={hasItems}>
<p>You have {itemCount} items in your cart.</p>
</template>
<template lwc:else>
<p>Your cart is empty.</p>
</template>
</template>The class turns the array into a count and a boolean.
// cart.js
import { LightningElement } from 'lwc';
export default class Cart extends LightningElement {
items = ['Pen', 'Notebook'];
get itemCount() {
return this.items.length;
}
get hasItems() {
return this.items.length > 0;
}
}The comparison this.items.length > 0 runs in JavaScript, where expressions are allowed. The template only reads the result.
Re-evaluation on change
The getter is read again each time the component re-renders. If items is reassigned, the framework re-renders, calls hasItems again, and swaps the branch. For example, this.items = [...this.items, 'Eraser'] triggers a re-render. The earlier chapter on reactive fields covers when a change counts.
Three or more branches
Use lwc:elseif when a value has more than two cases. Each branch needs its own getter, because the template cannot compare values.
<!-- stockStatus.html -->
<template>
<template lwc:if={isOutOfStock}>
<p>Out of stock</p>
</template>
<template lwc:elseif={isLowStock}>
<p>Only a few left</p>
</template>
<template lwc:else>
<p>In stock</p>
</template>
</template>// stockStatus.js
import { LightningElement } from 'lwc';
export default class StockStatus extends LightningElement {
stock = 3;
get isOutOfStock() {
return this.stock === 0;
}
get isLowStock() {
return this.stock > 0 && this.stock < 5;
}
}Branches are tested in order. When stock is 0, the first branch matches and the others are not considered. So isLowStock does not need to exclude zero, though the explicit check keeps the getter correct on its own.
Common errors
- Writing an expression in the directive.
lwc:if={items.length}andlwc:if={!hasItems}are not valid. Create a getter such asisEmptyfor the negated case. - Using the older directives.
if:trueandif:falsestill work in existing code, but they cannot express an else branch. Preferlwc:if,lwc:elseif, andlwc:elsein new code. - Separating the chain.
lwc:elseifandlwc:elsemust be placed on the sibling element that directly follows the previous branch. Putting another element between them breaks the chain. - Adding a value to
lwc:else. It is written bare, with no={...}.
Summary of the pattern
- Decide what the condition means in plain terms, such as "the cart has items".
- Write a getter that returns a boolean.
- Reference the getter in
lwc:if, and addlwc:elseiforlwc:elseas needed.
Exercise
A template contains <template lwc:if={items.length > 0}>. It fails to compile. What do you change in the template and in the class?
Show answer
In the class, add a getter such as get hasItems() { return this.items.length > 0; }. In the template, write <template lwc:if={hasItems}>. The template accepts only a property or getter reference, so the comparison must run in JavaScript.
Exercise
You need a template that shows "Loading" while isLoading is true, an error message when hasError is true, and the data otherwise. Which directives do you use, and in what order?
Show answer
Use lwc:if={isLoading} first, then lwc:elseif={hasError}, then lwc:else for the data. Branches are tested in order, so loading wins if both flags are true.