Using LWC Conditional directives lwc:if lwc:elseif and lwc:else

Using LWC Conditional directives lwc:if lwc:elseif and lwc:else


Hello Trailblazers!

In this post, we will see how to control the visibility of elements in the LWC template using the LWC conditional directives.

Previously we used if:true and if:false directives to conditionally show or hide the elements on the component. But from the Spring 2023 release, we will use a new lwc:if, lwc:elseif, and lwc:else directives.

The new conditional directives are more powerful and flexible than the legacy directives. They allow you to create complex conditional statements, and they also provide better performance.


The lwc:if directive

The lwc:if directive is used to render HTML if a condition is true. The condition can be a property, the result of an expression, or even a function call.

Example:

<template>
  <lightning-card title="Conditional Rendering">
    <div class="slds-m-around_medium">
      <template lwc:if={condition}>
        </template>
    </div>
  </lightning-card>
</template>


The lwc:elseif and lwc:else directives

The lwc:elseif and lwc:else directives are used to create more complex conditional statements.

The lwc:elseif directive is used to render HTML if a condition is true, but only if the previous conditions have been evaluated as false. 

The lwc:else directive is used to render HTML if all of the previous conditions have been evaluated to be false.

For example:

<template>
  <lightning-card title="Conditional Rendering">
    <div class="slds-m-around_medium">
      <template lwc:if={condition1}>
        </template>
      <template lwc:elseif={condition2}>
        </template>
      <template lwc:else>
        </template>
    </div>
  </lightning-card>
</template>


Best practices for using  lwc:if, lwc:elseif and lwc:else directives

  1. Use the lwc:if, lwc:elseif, and lwc:else directives instead of the legacy if:true and if:false directives.
  2. Keep your conditional statements as simple as possible. If you need to create a complex conditional statement, consider using a getter in your JavaScript class.
  3. Use comments to document your conditional statements, so that it is easy to understand what they are doing.


No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com