Sub topic 5
Using lwc:if on <template> and on elements
This chapter covers where you can put lwc:if (and its companions lwc:elseif and lwc:else) in a template. You can attach them to a <template> tag or directly to an HTML element. The two forms look similar, but they differ in what ends up in the DOM, how you group content, and which mistakes you are likely to make.
It assumes you can read an LWC HTML template and its JavaScript class, that you know how {property} binding works, and that you know how a getter returns a computed value.
The two placements
A directive is an attribute that tells the template compiler how to render a node. For conditional rendering you have two places to put it.
On a <template> tag, the template acts as an invisible wrapper:
<template>
<template lwc:if={isSignedIn}>
<h2>Welcome back</h2>
<p>Your last visit was {lastVisit}.</p>
</template>
</template>On an element, the directive controls only that element and everything inside it:
<template>
<p lwc:if={isSignedIn}>Welcome back, {userName}.</p>
</template>Both forms use the same rule. If the bound value is truthy, the node renders. If it is falsy, the node is not rendered and nothing for it exists in the DOM.
What the inner `<template>` does and does not produce
A nested <template lwc:if> tag is a compile-time construct. It never appears in the rendered DOM. Only its children do. When the condition is true, <h2> and <p> from the first example become direct children of whatever contains the template tag. When it is false, none of them exist.
An element with lwc:if is different. The element itself is part of the DOM when the condition is true, and it is absent when the condition is false.
| Aspect | `<template lwc:if>` | `<p lwc:if>` (any element) |
|---|---|---|
| Wrapper in the DOM | None | The element itself |
| Number of conditional nodes | One or more siblings | Exactly one element and its subtree |
| Extra markup needed | No | No |
| Typical use | Show a group of elements together | Show a single element |
Choosing between them
Use an element when only one element is conditional. It is shorter and keeps the structure flat:
<template>
<p lwc:if={hasItems}>You have {itemCount} items.</p>
<p lwc:else>Your list is empty.</p>
</template>Use <template> when a branch contains several sibling elements and you do not want to add a wrapper <div> just to hold the directive. An extra <div> can change layout, break a CSS rule that depends on direct children, or add a node to a list that expects specific children, such as <li> items inside a <ul>.
<template>
<ul>
<template lwc:if={showDetails}>
<li>Owner: {owner}</li>
<li>Created: {createdDate}</li>
</template>
<li>Name: {name}</li>
</ul>
</template>Here a <div> wrapper would put a non-<li> element inside the <ul>. The <template> form avoids that problem.
Placement can be mixed in a chain
A chain is a group of linked branches: one lwc:if, optional lwc:elseif branches, and an optional lwc:else. Each branch can use either form, and you can mix them within one chain.
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
<p>This may take a moment.</p>
</template>
<p lwc:elseif={hasError}>Something went wrong.</p>
<p lwc:else>Data is ready.</p>
</template>The first branch uses <template> because it has two elements. The other two use <p> because each has one. Exactly one branch renders at a time.
The chain rules covered later still apply: the branches must be adjacent siblings, and lwc:else takes no value. The diagram shows how the compiler reads the example above.
The value must be a simple reference
In every placement, the value of lwc:if and lwc:elseif must be a property or getter name in curly braces. It cannot be an expression. This is the same constraint whether you use <template> or an element.
<template>
<!-- Valid -->
<p lwc:if={isAdmin}>Admin tools</p>
<!-- Invalid: expressions are not allowed in the template -->
<!-- <p lwc:if={role === 'admin'}>Admin tools</p> -->
</template>Move the comparison into a getter:
import { LightningElement, api } from 'lwc';
export default class RoleBadge extends LightningElement {
@api role = 'guest';
get isAdmin() {
return this.role === 'admin';
}
}The getter works for either placement. Treat this as a rule of the template language, not a style preference.
Where directives do not apply
Some placement choices cause errors or surprises.
- Two conditional directives on one node. An element takes one conditional directive. Writing
lwc:ifandlwc:elseon the same tag, or combininglwc:ifwith the legacyif:true, is not allowed. Pick one. - Directives on the root
<template>. The outermost<template>of a component is the component's own template. Do not putlwc:ifon it. Wrap the conditional content in an inner<template>or element instead. - Plain
<template>with no directive. An inner<template>with no directive has no effect. Addlwc:if,for:each, or another directive to make it do something. - Slots and conditionals. A
<slot>can sit inside a conditional branch, but the slot content comes from the parent. If the branch is not rendered, the slot is not rendered either.
Effects on CSS and layout
Since an inner <template> leaves no node behind, selectors in your component CSS see only the real elements. For example, a selector like ul > li matches the <li> elements from the earlier list whether or not they came from a <template lwc:if>.
An element with lwc:if leaves a real node when true, so any styling on it applies as usual. When false, it leaves nothing. That means :first-child and :last-child selectors can match different elements as the condition changes. If a style depends on which child is first or last, test both states.
Events and references
Because a false branch has no DOM, anything inside it cannot be found. this.template.querySelector('p') returns null for a paragraph in a branch that is not rendered. This holds for both forms.
import { LightningElement } from 'lwc';
export default class Greeting extends LightningElement {
isSignedIn = false;
handleSignIn() {
this.isSignedIn = true;
// The paragraph is not in the DOM yet during this call.
const early = this.template.querySelector('.welcome');
console.log(early); // null
// After the next render, the paragraph exists.
Promise.resolve().then(() => {
const late = this.template.querySelector('.welcome');
console.log(late); // the <p> element
});
}
}<template>
<button onclick={handleSignIn}>Sign in</button>
<p class="welcome" lwc:if={isSignedIn}>Welcome back.</p>
</template>Changing a field does not render synchronously. The framework batches the change and re-renders afterward, so query the DOM after that render, for example in renderedCallback, or use a microtask as shown.
Worked comparison
Suppose you want a notice with an icon, a title, and a message, shown only for a warning state.
Option A uses an element wrapper:
<template>
<div class="notice" lwc:if={isWarning}>
<span class="icon">!</span>
<strong>{title}</strong>
<span>{message}</span>
</div>
</template>Option B uses a <template>:
<template>
<template lwc:if={isWarning}>
<span class="icon">!</span>
<strong>{title}</strong>
<span>{message}</span>
</template>
</template>Option A keeps a .notice container, so you can style the box, add padding, or give it a border. Option B has no container, so the three children sit directly in the parent. Choose A when the group needs its own box. Choose B when the group should blend into the parent's layout.
Common mistakes with placement
- Adding a
<div>only to holdlwc:if, which can break list or grid structure. Use<template>. - Using
<template>and expecting a styled box. It adds no node, so there is nothing to style. - Writing an expression instead of a property or getter name.
- Putting the directive on the component's root
<template>. - Querying for elements in a branch that has not rendered yet.
Exercise
A <ul> must show two extra <li> items only when showDetails is truthy, and you must not add any element that is not an <li> inside the <ul>. Which placement do you use, and what does the DOM contain when showDetails is false?
Show answer
Use <template lwc:if={showDetails}> around the two <li> elements. The <template> tag leaves no node in the DOM, so the extra items are direct children of the <ul> when true. When showDetails is false, none of the two <li> elements and no wrapper exist in the DOM.
Exercise
Why does <p lwc:if={role === 'admin'}>Admin</p> fail, and how do you fix it?
Show answer
The value of lwc:if must be a property or getter reference, not an expression. Add a getter such as get isAdmin() { return this.role === 'admin'; } and write <p lwc:if={isAdmin}>Admin</p>.