What is Conditional Rendering in LWC?
Conditional rendering in the lightning web component (lwc) is a way to display components or elements based on a specific condition. For instance, you can display different greeting messages depending on the time of day.
Conditional Rendering in LWC using lwc:if, lwc:elseif and lwc:else.
Let see how to use lwc:if, lwc:elseif and lwc:else in lightning web components. With the new lwc:if
, lwc:elseif
, and lwc:else
conditional directives, the property getters are accessed only one time per instance of the directive. Here is an example of how we can use it.
<template>
<template lwc:if={expression1}>
Statement 1: Hi
</template>
<template lwc:elseif={expression2}>
Statement 2 : Hello
</template>
<template lwc:else>
Statement 3 : How are you?
</template>
</template>
The legacy if:true
and if:else
directives are no longer recommended as Salesforce intends to deprecate and remove these directives in the future. Salesforce recommend that you replace their usage with the new conditional directives to future-proof your code
if:true and if:false
This is conditional rendering using if:true and if:false:
<template>
<template if:true={condition1}> Hello Apex Hours </template>
<template if:false={condition1}>
<template if:true={condition2}> If </template>
<template if:false={condition2}> Else </template> </template> </template>
Consideration for lwc:if, lwc:elseif and lwc:else
- You can’t precede
lwc:elseif
orlwc:else
with text or another element. - 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.
0 Comments