How to write If Else conditions in LWC

Spring 23 release, salesforce introduced lwc:if, lwc:elseif and lwc:else conditional directives in lightning web components. Using these directives we can control the rendering of html elements. here is the example component to using if and else conditions.

Conditional Rendering in LWC

ifElseConditions.html

<template>
    <template lwc:if={condition1}>
        If condition 
    </template>
    <template lwc:elseif={condition2}>
        Else if condition 
    </template>
    <template lwc:else>
        else condition
    </template>
</template>

ifElseConditions.js

import { LightningElement } from 'lwc';

export default class IfElseConditions extends LightningElement {
    condition1 = false;
    condition2 = true;
}

ifElseConditions.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>56.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Also found above code in Tech Shorts Git repo

Labels:
LWC
Join the conversation