template if:true Conditional Rendering LWC

template if:true Conditional Rendering LWC

template if:true Conditional Rendering LWC(Lightning Web Component)

To render HTML conditionally, add the if:true|false directive to a nested <template> tag that encloses the conditional content. template if:true|false directive is used to display conditional data.

Render DOM Elements Conditionally Lightning Web Component

The if:true|false={property} directive binds data to the template and removes and inserts DOM elements based on whether the data is a truthy or falsy value.

 

template if:true  LWC Example

Let’s see a simple example to show content based on the selection of checkbox. Example contains a checkbox labeled Show details. When a user selects or deselects the checkbox., based on that content is visible. This example has been copied from official link.

templateIFTrueExampleLWC.html

<template>
    <lightning-card title="TemplateIFTrueConditionalRendering" 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>

templateIFTrueExampleLWC.js

import { LightningElement } from 'lwc';
export default class TemplateIFTrueExampleLWC extends LightningElement {
    areDetailsVisible = false;
    handleChange(event) {
        this.areDetailsVisible = event.target.checked;
    }
}

templateIFTrueExampleLWC.js-meta.xml

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

Now we can add this lwc component on home page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your templateIFTrueExampleLWC component and drag it on right hand side top.
  • Click Save and activate.

 

We will get the following Output

template if true Conditional Rendering LWC

 

When user select the checkbox, we will see the following output

template if true Conditional Rendering LWC selected

 

Let’s see some practical example. In this example, account list is fetched from the database. If there is some error in fetching account list then show error otherwise show account list

AccountHelper.cls

public with sharing class AccountHelper {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Type, Rating,
                Phone, Website, AnnualRevenue
            FROM Account];
    }
}

accountListForEachLWC.html

<template>
    <lightning-card title="Account List using for:each" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <template if:true={accounts.data}>
                <template for:each={accounts.data} for:item="acc">
                    <p key={acc.Id}>{acc.Name}</p>
                </template>
            </template>
            <template if:true={accounts.error}>
                {accounts.error}
            </template>
        </div>
    </lightning-card>
</template>

accountListForEachLWC.js

import { LightningElement, wire } from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
export default class AccountListForEachLWC extends LightningElement {
    @wire(getAccountList) accounts;
}

For full detail about this example, please refer to for:each template directives in LWC

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/template-iftrue-conditional-rendering-lwc/

7 comments

Skip to comment form

    • Vis55 on May 22, 2020 at 4:21 am
    • Reply

    If AccountHelper.getAccountList returns 0 rows, how do we update the HTML template with any readable text like ‘No data found’ . Can you please provide the updated java script and HTML code ?

    1. There are multiple ways of doing that. One way is that you can check list size in javascript controller and based on that you can update boolen variable. Use that boolean variable in template if true

      Another way is simply use

      <template if:false={accounts.data}>
      <!--code here -->
      </template>
      
  1. Pretty! This was an extremely wonderful post.
    Many thwnks for providing this information.

    • Anu on December 1, 2020 at 12:53 pm
    • Reply

    I have 3 Boolean variables in js. I want to display a template if any one of the 3 Boolean variables are true. Could you please tell me how to achieve this.

    • Bhaskar on December 14, 2020 at 8:33 pm
    • Reply

    I have Start and end date selected both the dates now i want to disable those selected dates and new row has to pop up with the start and end date. In this row the previous end date should be as start date. I want to do using LWC. Please let me know how to do

    thank you

    • Shirish on April 7, 2021 at 5:18 pm
    • Reply

    can you please let me know how can we achieve the conditional rendering while writing the unit test cases?

    • Jasmine on May 6, 2021 at 6:03 pm
    • Reply

    will this automatically handle the error?
    {accounts.error}

Leave a Reply

Your email address will not be published.