Improved Conditional Directives (lwc:if vs if:true ) LWC salesforce spring'23 release

 

Use the Improved Conditional Directives

The lwc:iflwc:elseif, and lwc:else conditional directives supersede the legacy if:true and if:else directives.

Where: This change applies to custom Lightning web components in Lightning Experience, Experience Builder sites, and all versions of the Salesforce mobile app. This change also applies to Lightning web components in Open Source.

How: With the lwc:iflwc:elseif, and lwc:else conditional directives, the property getters are accessed only one time per instance of the directive.

<!-- conditionalExample.html -->
<template>
    <template lwc:if={isTemplateOne}>
        This is template one.
    </template>
    <template lwc:else>
        This is template two.
</template>

Both lwc:elseif and lwc:else must be immediately preceded by a sibling lwc:if or lwc:elseif.

Pass in an expression to lwc:if and lwc:elseif, but not to lwc:else.

If expression1 returns a truthy, none of the other property getters are accessed.

<!-- example.html -->
<template>
    <template lwc:if={expression1}>
        Statement 1
    </template>
    <template lwc:elseif={expression2}>
        Statement 2
    </template>
    <template lwc:else>
        Statement 3
    </template>
</template>

Previously, chaining if:true and if:false blocks introduced performance cost and resulted in the property getters getting called multiple times.

<!-- legacyConditional.html -->
<template>
    <!---Replace if:true with lwc:if-->
    <template if:true={isTemplateOne}> 
        This is template one.
    </template>
    <!-- Replace if:false with lwc:else -->
    <template if:false={isTemplateOne}> 
        This is template two.
    </template>
</template>
Important
IMPORTANT The legacy if:true and if:else 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 new conditional directives to future-proof your code.

Consider these guidelines when working with the lwc:iflwc:elseif, and lwc:else conditional directives.

  • 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 or lwc: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 after lwc:if and before lwc:else.
  • Complex expressions like !condition or object?.property?.condition aren’t supported. To evaluate complex expressions, use a getter in your JavaScript class.

Comments

Popular posts from this blog

IsVisibleInSelfService on Task salesforce

Too many batch retries in the presence of Apex triggers and partial failures.

Governor limit SOQL 101 being suppressed