Render DOM Elements Conditionally
To render HTML conditionally, add the lwc:if|elseif={property}
and lwc:else
directive to a tag that encloses the conditional content. You can use the conditional directives on nested <template>
tags and HTML standard tags such as <div>
. You can also use conditional directives with your custom component tags like <c-custom-cmp>
or base component tags like <lightning-spinner>
.
Directives are special HTML attributes. The Lightning Web Components programming model has a few custom directives that let you manipulate the DOM using markup.
The lwc:if|elseif
directives bind {property}
to the template, removing and inserting DOM elements based on whether the data is a truthy or falsy value.
The legacy if:true
and if:false
directives are no longer recommended as we intend to deprecate and remove these directives in the future. We recommend that you replace their usage with the lwc:if|elseif|else
conditional directives to future-proof your code.
This example has two properties property1
and property2
.
Only one of the three statements renders:
Statement1
renders ifproperty1
is true.Statement2
renders ifproperty1
is false andproperty2
is true.Statement3
renders ifproperty1
andproperty2
are false.
Although the example uses all three directives, lwc:elseif
and lwc:else
are optional.
Let’s look at another example. This template contains a checkbox labeled Show details. When a user selects or deselects the checkbox, the handleChange
function sets the value of the areDetailsVisible
property. If the areDetailsVisible
property is true
, the lwc:if
directive renders the nested template, which displays These are the details!.
Notice that the JavaScript doesn’t manipulate the DOM, it simply changes the value of a property.
To toggle the value of a boolean property in markup, default the value to false
. See Boolean Properties.
This sample code is the helloConditionalRendering
component from the github.com/trailheadapps/lwc-recipes repo. For an example that uses a conditional directive on an HTML element, such as a div
element, see the helloIterator
component.
See Also