Ad
Ad
Ad
Lightning Web Components

Conditional Rendering in Lightning Web Components

Pinterest LinkedIn Tumblr

 Conditional Rendering in Lightning Web Components

In this post, We will try to understand how to Conditionally render different DOM Elements in Lightning Web Component. The power of Lightning web components comes from its ability to display dynamic or desired DOM Elements based on Conditional directive. Salesforce provides us with two if directives such as <if:true> and < if:false> in order to display desired DOM Element.

Html file(electric.html):

<template>

<div id=”electriccar” if:false={pageload}>

<div>Name: {name}</div>

<div>Description: {description}</div>

</div>

<div id=”regularCar” if:true={pageload}>

<div>Car Type: {cartype}</div>

<div> Mileage:{mileage} </div>

</div>

</template>

JavaScript file(electric.js)::  In Javascript file add details for the property and set pageload property as false as shown below.

import { LightningElement } from ‘lwc’;

export default class Electric extends LightningElement {

name = ‘Tesla’;

description = ‘Tesla is an Electric Car.’;

cartype = ‘Regular Car’;

mileage = ’30’;

pageload = false;

}

The above will display the following output as we have set the pageload property as false in javascript. In our HTML file(electric.html) we are comparing if:false directive with pageload property and since the value of false matches on both sides we are conditionally displaying Name and Description fields.

Try it in playground: https://developer.salesforce.com/docs/component-library/tools/playground

Write A Comment