Sub topic 1
Conditional Rendering in Lightning Web Components
Prerequisites
This chapter assumes basic HTML and JavaScript, including classes and getters. You should also know how an LWC template binds to reactive fields with curly braces.
Quick refresher: binding properties in a template
An LWC template reads public or private component properties with {propertyName}. When a reactive property changes, LWC updates the relevant part of the rendered page.
<template>
<p>Hello, {name}!</p>
</template>import { LightningElement } from 'lwc';
export default class Greeting extends LightningElement {
name = 'Ada';
}The template does not contain business logic. It reads values supplied by the component class.
Why render conditionally?
Conditional rendering means adding content only when a condition is met. It keeps unavailable content out of the DOM (Document Object Model), which represents the page structure.
For example, a component might show a loading message while data is being fetched and show the data after the request finishes. Conditional rendering also avoids presenting controls that a user cannot currently use.
How a condition is evaluated: truthy and falsy values
lwc:if evaluates a bound value using JavaScript truthiness. Truthy values render the branch. Falsy values do not.
Common falsy values include false, 0, '' (an empty string), null, and undefined. Objects and arrays are truthy, even when they are empty.
Showing content with `lwc:if`
Place lwc:if on an element or a <template> tag. The value must be a property reference or getter reference.
<template>
<template lwc:if={hasAccount}>
<p>Account details are available.</p>
</template>
</template>When hasAccount changes from falsy to truthy, LWC renders the paragraph. When it changes back, LWC removes it.
Using `lwc:if` on `<template>` and on elements
Use a <template> wrapper when several elements belong to one conditional block:
<template lwc:if={isReady}>
<h2>Ready</h2>
<p>The results can be viewed.</p>
</template>For one element, put the directive directly on that element:
<p lwc:if={hasItems}>Your list has items.</p>Computing conditions with getters
A getter is a method read like a property. Use one when the condition requires comparison or other JavaScript logic.
get hasAccount() {
return this.account?.id !== undefined;
}The template can then use {hasAccount}. When a value used by the getter changes, LWC reevaluates the getter during rendering.
Exercise
Should a template contain lwc:if={status === 'ready'}?
Show answer
No. Put the comparison in a JavaScript getter, then bind lwc:if to that getter.