
As a developer, one of the most important aspects of building web applications is the ability to control the flow of data and elements on a page. The Lightning Web Components (LWC) framework, which is used to build web applications on the Salesforce platform, provides several directives that allow developers to control the flow of elements on a page.
In this blog post, we will discuss the lwc:if, lwc:elseif, and lwc:else conditional directives introduced in the Spring’23 release and how they supersede the legacy if:true and if:else directives.
The lwc:if directive is used to conditionally render elements on a page based on a boolean expression. The syntax for the lwc:if directive is as follows:
<template> | |
<template lwc:if={isTemplateOne}> | |
This is template one. | |
</template> | |
<template lwc:else> | |
This is template two. | |
</template> |
The lwc:elseif and lwc:else directives are used in conjunction with the lwc:if directive to provide additional control over the flow of elements on a page. The lwc:elseif directive is used to render elements if the condition specified in the lwc:if directive is false, and a different condition is true.
The lwc:else directive is used to render elements if none of the conditions specified in the lwc:if and lwc:elseif directives are true.
The syntax for the lwc:elseif directive is as follows:
<template> | |
<template lwc:if={expression1}> | |
Statement 1 | |
</template> | |
<template lwc:elseif={expression2}> | |
Statement 2 | |
</template> | |
<template lwc:else> | |
Statement 3 | |
</template> | |
</template> |
Note: The legacy if:true and if:else directives are no longer recommended because Salesforce intends to deprecate and remove them in the future.
Consider the following guidelines when working with the lwc: Conditional directives if, lwc:elseif, and lwc:else.
- Use the conditional directives on nested
<template>
tags,<div>
tags, or other HTML elements, and on your custom components tags like<c-custom-cmp>
. - You can’t precede
lwc:elseif
orlwc:else
with text or another element. Whitespace is ignored between the tags when the whitespace is a sibling of the conditional directive. For example, you can’t have a<div>
tag that comes afterlwc:if
and beforelwc:else
. - Complex expressions like
!condition
orobject?.property?.condition
aren’t supported. To evaluate complex expressions, use a getter in your JavaScript class.
In conclusion, the lwc:if, lwc:elseif, and lwc:else directives are powerful tools for controlling the flow of elements on a page in the Lightning Web Components framework. They provide a more consistent and intuitive syntax than the legacy if:true and if:else directives, and it is recommended to use them in new development.