Conditional rendering in lightning web component
To show any content on some condition we need to use conditional rendering in LWC.
Like Aura Components <Aura:if>, apex (if, else) the same way we have <template if:true> and <template if:false>in Lightning web component.
In this post, we will implement the functionality to use template if:true in LWC (Lightning Web Components) with Conditional Statements. template if:true in LWC is used for Conditional Rendering to display markup or DOM elements dynamically if true value is provided. template if:false works in the same way but with the false value. But template if:true or template if:false does not support the Conditional Statements. For example, we can write template if:true={boolVariable} but we can not write template if:true={number>10}.
Follow below Steps
-----------------------
Step 1 :- Make HTML File.
<template>
<lightning-card title="Conditional Rendering in LWC">
<div>
<lightning-button label="Show first name" onclick={showFirstName}>
</lightning-button>
<lightning-button label="Show last name" onclick={showLastName}>
</lightning-button>
</div>
<div class="slds-text-heading_large">
<template if:true={fname}>
<h1>First name is Khumed</h1>
</template>
<template if:true={lname}>
<h1>Last name is Khatib</h1>
</template>
</div>
</lightning-card>
</template>
Step 2 :- Make Javascript File.
import { LightningElement ,track} from 'lwc';
export default class RerebdingOfLwc extends LightningElement {
@track fname = false;
@track lname = false;
showFirstName() {
this.fname=true;
this.lname=false;
}
showLastName() {
this.fname=false;
this.lname=true;
}
}
Step 3:- Make Meta.XML file
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightningCommunity__Page</target>
<target>lightningCommunity__Default</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
OUTPUT OF ABOVE CODE CODE
Press Show First Name Button It will Show First Name
Press Show Last Name Button It will Show Last Name
******************************
Like our post & bookmark this blog for your future learning.
Any suggestions and improvements are most welcome, please comment your suggestions and improvement in the comment box.
Happy Coding Sharing Is caring. 😀😀😀
Post a Comment