Hello Salesforce Folks !!
In my previous post, I had told you about the http://forceblogs.com/alertbox-alert-your-users-in-salesforce-dynamically/ .
Today, Let’s us discuss about the use of the conditional rendering in custom Lightning Web Component (LWC) with HTML template <template if:true> and <template if:false> directive to conditionally render DOM elements in a template.
As the directives are some HTML tags, like if:true and for:each by which we can manipulate the DOM in markup.
So, you know we can bind the data in a component’s template to the {property} of component javascript class.
The directive if:true|false={property} based on whether the data has true or false value.
In the nested <template> tag add the if:true|false={property} directives if you want to render the HTML conditionally that enclosing with the conditional logic.
What is conditional rendering in Salesforce Lightning Web Component Framework?
When we need to add conditional rendering in Lightning Web component, we can use HTML Template Directives with <template if:true> and <template if:false> tag.
Now, let’s begin with the Code.!
Step 1: Create the Lightning Web Component
<!-- HelloWorld.html --->
<template>
<div class="slds-box">
<h2 class="header">Toggle</h2>
<div class="slds-m-around_medium">
<template if:true={isDisplayName}>
{Name1}
</template>
</div>
<lightning-input type="toggle" label="Display" name="input1" onchange={handleToggleChange}></lightning-input>
</div>
</template>
In javascript, you only need to add or change in the value of the property.
// HelloWorld.js
import { LightningElement,track } from 'lwc';
export default class Toggle extends LightningElement {
@track Name1;
@track isDisplay;
handleToggleChange(event) {
this.Name1 = 'Hello World' ;
this.isDisplay = !this.isDisplay;
}
get isDisplayName() {
return this.isDisplay;
}
}
Let us know in the comment section if this component helps you out. !!
If you have any issue with Conditional Rendering component, or you want to extend this component further Chat with us, We will be more than happy to assist you.