Conditional Rendering in LWC : jayakrishnasfdc

Conditional Rendering in LWC
by: jayakrishnasfdc
blow post content copied from  Jayakrishna Ganjikunta
click here to view original post


Conditional Rendering:

If we want to hide some of the components from the HTML and show it based on conditions then we can use conditional rendering.

To render a DOM element in a template only when certain conditions are met, we use conditional rendering.

Like Aura Components <Aura:if>, apex (if, else) the same way we have <template if:true> and <template if:false>in Lightning web component.

==> If the value of the if:true expression changes and evaluates to false, all the components inside the <template if:true= {}> tag are destroyed. The components are created again if the if:true expression changes again and evaluates to true.

==> If the value of the if:false expression changes and evaluates to true, all the components inside the <template if:false= {}> tag are destroyed. The components are created again if the if:false expression changes again and evaluates to false.

Sample Example:

conditionalRendering.html

<!-- helloConditionalRendering.html -->
<template>
    <lightning-card title="HelloConditionalRendering" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <lightning-input type="checkbox" label="Show details" onchange={handleChange}></lightning-input>
            <template if:true={areDetailsVisible}>
                <div class="slds-m-vertical_medium">
                    These are the details!
                </div>
            </template>
        </div>
    </lightning-card>
</template>

conditionalRendering.js

// helloConditionalRendering.js
import { LightningElement } from 'lwc';

export default class HelloConditionalRendering extends LightningElement {
    areDetailsVisible = false;

    handleChange(event) {
        this.areDetailsVisible = event.target.checked;
    }
}
Checkbox labeled Show details.
Checkbox with Show Details checked and detail text displaying beneath.

Other Example:

ifExp.html

<template>    
<div>        
<template if:true={isTom}>           
| <p>This is Tom</p>       
</template>        
<template if:false={isJerry}>            
<p>This is Jerry</p>        
</template>    
</div>
</template>

ifExp.js

import { LightningElement } from ‘lwc’;
export default class IfExp extends LightningElement {
    isTom =true;
    isJerry=false;
}

Output:


December 05, 2020 at 04:59PM
Click here for more details...

=============================
The original post is available in Jayakrishna Ganjikunta by jayakrishnasfdc
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce