Sub topic 4
Showing content with lwc:if
This chapter covers the lwc:if directive. It assumes you can read a Lightning Web Component (an HTML template plus a JavaScript class). It also assumes you know how to bind a property with curly braces and how to handle a click event. The chapter shows how a condition adds and removes DOM, which values count as true, and where the directive can go. Later chapters cover fallback and extra branches.
Why render conditionally?
Most components do not show the same thing all the time. A record form might show a spinner while it loads, a message when it fails, and the fields when it succeeds. Conditional rendering lets the template describe each of these states and lets the component's data decide which one appears.
In LWC, the template contains no JavaScript logic. It only references properties and getters on the class. The lwc:if directive takes one such reference and decides whether the element it sits on exists in the DOM.
The basic form
Here is a minimal component.
<template>
<button onclick={handleToggle}>Toggle details</button>
<template lwc:if={showDetails}>
<p>Here are the details.</p>
</template>
</template>import { LightningElement } from 'lwc';
export default class DetailsToggle extends LightningElement {
showDetails = false;
handleToggle() {
this.showDetails = !this.showDetails;
}
}When showDetails is false, the paragraph is not in the DOM at all. Clicking the button flips the field. LWC re-renders the template, sees a truthy value, and inserts the paragraph. Clicking again removes it.
Class fields are reactive in LWC. Assigning a new value to showDetails triggers a re-render without any decorator.
How a condition is evaluated
lwc:if does not require a boolean. It checks whether the value is truthy or falsy using the normal JavaScript rules.
These values are falsy, so the block is not rendered:
false0and-0""(empty string)nullundefinedNaN
Everything else is truthy, and the block renders. That includes some values that surprise people:
| Value | Truthy? | Note |
|---|---|---|
| `"false"` | Yes | Any non-empty string is truthy, even the text "false". |
| `"0"` | Yes | A non-empty string, not the number zero. |
| `[]` | Yes | An empty array is still an object. |
| `{}` | Yes | An empty object is truthy. |
| `0` | No | The number zero is falsy. |
| `undefined` | No | A field that has not been set yet is falsy. |
The empty array is the most common source of bugs. If you write lwc:if={contacts} and contacts is [], the block renders with nothing in it. To test for content, use a getter, shown below.
The undefined case is useful. Data that has not arrived yet is usually undefined or null, so lwc:if={account} naturally waits until the data exists.
Using lwc:if on a template tag and on an element
You can put the directive on a <template> tag or directly on an element.
<template>
<!-- On a wrapping template tag: controls several elements at once -->
<template lwc:if={isLoggedIn}>
<h2>Welcome back</h2>
<p>Your last visit was recently.</p>
</template>
<!-- On an element: controls only that element -->
<p lwc:if={hasItems}>You have {itemCount} items.</p>
</template>A <template> tag with a directive is a wrapper that produces no DOM element of its own. Its children are inserted directly where it sits. Use it when several siblings appear and disappear together, so you do not need an extra <div> that could break your CSS layout.
When only one element is conditional, put lwc:if on that element. This is shorter and has the same effect.
Computing conditions with getters
The value in lwc:if must be a plain reference such as {isVisible} or {account.isActive}. You cannot write an expression in the template.
<template>
<!-- None of these are valid -->
<p lwc:if={!isVisible}>Hidden</p>
<p lwc:if={count > 0}>Has items</p>
<p lwc:if={a && b}>Both</p>
</template>The template compiler rejects all three. To express negation, comparison, or a combination, write a getter in the class. A getter is a method declared with get that you read like a property.
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts = [];
isAdmin = false;
get hasContacts() {
return this.contacts.length > 0;
}
get isEmpty() {
return !this.hasContacts;
}
get canDelete() {
return this.isAdmin && this.hasContacts;
}
handleLoad() {
this.contacts = [
{ id: '1', name: 'Ada Lovelace' },
{ id: '2', name: 'Grace Hopper' }
];
}
}<template>
<button onclick={handleLoad}>Load contacts</button>
<p lwc:if={isEmpty}>No contacts yet.</p>
<template lwc:if={hasContacts}>
<ul>
<template for:each={contacts} for:item="contact">
<li key={contact.id}>{contact.name}</li>
</template>
</ul>
</template>
<button lwc:if={canDelete}>Delete all</button>
</template>A getter re-runs whenever the template re-renders. It also depends on reactive fields it reads. Here, assigning a new array to contacts causes hasContacts and isEmpty to be re-evaluated, and the DOM updates.
Name getters for the state they describe, such as hasContacts or canDelete. The template then reads almost like a sentence.
Placement rules specific to lwc:if
- The value must be wrapped in curly braces.
lwc:if="true"with a string literal is an error, because the directive expects a binding. - The directive cannot go on the root
<template>element of the component. The root template is the component itself. Wrap the content in a nested<template lwc:if={...}>instead. - Each
lwc:ifstarts a new conditional block. Two separatelwc:ifdirectives next to each other are independent. Both can render at once if both values are truthy.
<template>
<p lwc:if={isAdmin}>Admin tools</p>
<p lwc:if={hasContacts}>Contact tools</p>
</template>Here either paragraph, both, or neither can appear. Chapters on lwc:elseif and lwc:else show how to link branches so that only one renders.
What the directive does to the DOM
When a value becomes falsy, LWC removes the block from the DOM. It does not just hide it. If the block contains a child component, that component is disconnected and destroyed. Local state inside it is lost. When the value becomes truthy again, LWC creates a new instance. A later chapter covers the lifecycle hooks involved.
You can see this with a simple experiment. Put an <input> inside a block, type in it, toggle the condition off and on, and notice the text is gone. The browser created a fresh input.
Common mistakes with lwc:if
- Writing an expression.
lwc:if={count > 0}does not compile. Use a getter. - Testing an array directly.
lwc:if={items}is true for[]. Testitems.lengththrough a getter. - Expecting string values to be parsed. A field holding
"false"is truthy. Store real booleans. - Mutating in place. If the condition depends on a nested value you change without reassigning, the template may not update as you expect. Reassign the field or the object so the change is visible.
- Using the directive on the root template. Wrap content in an inner
<template>.
Exercise
A component has the field results = []. The template contains <template lwc:if={results}><p>Found results</p></template>. The paragraph appears even before any search runs. Why, and how do you fix it?
Show answer
An empty array is an object, and every object is truthy in JavaScript, so lwc:if renders the block. Add a getter get hasResults() { return this.results.length > 0; } and change the template to lwc:if={hasResults}.
Exercise
Why does <p lwc:if={count > 0}>Items</p> fail, and what is the smallest change that makes it work?
Show answer
The directive accepts only a property or getter reference, not an expression. Define get hasCount() { return this.count > 0; } in the class and use lwc:if={hasCount}.