New Spring '23 Conditional Statements in Lightning Web Component Salesforce| lwc:if, lwc:elseif & lwc:else | LWC Stack ☁️⚡️


 Recently salesforce has introduced new conditional statements in its Spring '23 release for Lightning Web Components.

Before this new update we were having template if:true={var} and template if:false={var} to check if a condition is true or false. But now in its new release we have new conditional statements lwc:if, lwc:elseif & lwc:else.

In this blog I will show you how you can use it in your lightning web component. In below example we are having two variables in JavaScript. (one, two)
If one is true then we will display 1 on the output, if one is false but two is true then we will display 2 on the output and if none of them are true then we will display 3 on the output.

In below example you will be able to understand how we were doing it before Spring '23 release.

Example 1: Using the standard way (Before Spring '23)

HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<template>
    <lightning-card  variant="Narrow"  title="Conditional Statements" icon-name="standard:account">
        <div class="slds-p-around_large">
        <template if:true={one}>
            1
        </template>
        <template if:false={one}>
            <template if:true={two}>
                2
            </template>
            <template if:false={two}>
                3
            </template>
        </template>
        </div>
    </lightning-card>
</template>

JS

1
2
3
4
5
6
import { LightningElement } from 'lwc';

export default class ConditionalStatement extends LightningElement {
    one = false;
    two = false;
}

Example 2: New Way (Spring '23)

HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<template>
    <lightning-card  variant="Narrow"  title="Conditional Statements Spring 23" icon-name="standard:account">
        <div class="slds-p-around_large">
            <template lwc:if={one}>
                1
            </template>
            <template lwc:elseif={two}>
                2
            </template>
            <template lwc:else>
                3
            </template>
        </div>
    </lightning-card>
</template>


JavaScript is same for this one.

Output



You will not notice any change in UI but in the backend it can save bunch of lines in code for you.


Checkout complete video tutorial below


 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments