template if:true in LWC with Conditional Statements

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}.

This is easily achievable in Aura Components using aura:if isTrue={!v.number > 10} but in LWC, we need to go with some workaround. And if you want to know it, you are in the right place. Let’s hop into the implementation.

Implementation

To implement template if:true in LWC with Conditional Statements, we need to make use of Child Components. In this implementation, we will have the list of Accounts in the Parent Component. Child Component is used to display Account details for a single Account. Once the Account Name is selected from the Dropdown, the respective Child Component will be rendered to display the Account details.

This is how our implementation will look:

template if:true in LWC with Conditional Statements
template if:true in LWC with Conditional Statements

template if:true in LWC with Conditional Statements

We will display the details of Account conditionally so first, create a Lightning Web Component cardCmp and use a lightning-card to display Account details. Keep the entire card in template if:true={showCard} so that, if showCard is true, only then, the Account details will be displayed.

cardCmp.html

<template>
    <template if:true={showCard}>
        <lightning-card  title={account.Name}>
            <p class="slds-p-horizontal_large">
                Email: {account.Email}
                <br/>
                Other Details
            </p>
        </lightning-card>
    </template>
</template>

In the carcCmp.js, declare two public variables selectedAccount and account using @api decorator. We are making it public so that we can pass these values from the Parent component that we will create later. Then, add a Getter showCard that will return true if selectedAccount is equal to account.Name. Else it will return false. And remember, based on this Getter showCard, the current Account details card will be displayed.

import { LightningElement, api } from 'lwc';

export default class CardCmp extends LightningElement {
    @api selectedAccount;
    @api account;

    get showCard(){
        if(this.selectedAccount == this.account.Name)
            return true;
        return false;
    }
}

Before moving ahead, if you want to know how Javascript Properties including public properties and Getters works, you can check this implementation.

Now, create a Lightning Web Component conditional. Add two arrays to store the Accounts details in lstAccounts and values for Dropdown list in listValues. Once the Account Name is selected from the Dropdown list, save the Account Name in currentAccount property using onchange handler accountChanged.

conditional.js

import { LightningElement, track } from 'lwc';

export default class Conditional extends LightningElement {
    currentAccount;
    
    @track lstAccounts = [
        {
            'Name' : 'Cristiano Ronaldo',
            'Email' : 'abc@example.com'
        },
        {
            'Name' : 'Lionel Messi',
            'Email' : 'xyz@exmaple.com'
        },
        {
            'Name' : 'Sachin Tendulkar',
            'Email' : 'pqr@example.com'
        }
    ];

    @track listValues = [
        { label: 'Cristiano Ronaldo', value: 'Cristiano Ronaldo' },
        { label: 'Lionel Messi', value: 'Lionel Messi' },
        { label: 'Sachin Tendulkar', value: 'Sachin Tendulkar' }
    ];

    accountChanged(event){
        this.currentAccount = event.detail.value;
    }

}

In a real project, the Account record will be fetched from the Salesforce database using Apex. To keep this implementation short, I have stored the data on the client-side. If you want to know how multiple ways to Apex method from Lightning Web Component, you can check this implementation.

In the HTML file, use lightning-combobox to display the dropdown and add the change handler that will call accountChanged to save the selected Account Name in currentAccount property. Then, use the template for:each loop to loop through the lstAccounts. This loop is used to display all the Account records in the component. But only one Account will be displayed at a time based on the Account Name selected in the Dropdown. Inside the loop, add the child component cardCmp and pass the currentAccount to selectedAccount property and Account record acc to account property of cardCmp component.

<template>
    <lightning-card  title="Conditional TEMPLATE IF:TRUE">
        <div class="slds-p-around_small">
            <lightning-combobox
                name="selectAccountName"
                label="Select Account to display:"
                value={currentAccount}
                placeholder="SelectAccount"
                options={listValues}
                onchange={accountChanged} ></lightning-combobox>

                <br/>

            <template for:each={lstAccounts} for:item="acc">
                <c-card-cmp key={acc.Name} selected-account={currentAccount} account={acc}></c-card-cmp>
            </template>
        </div>
    </lightning-card>
</template>

Before going crazy, let me tell you what will happen here. As soon as we select the Account Name from the Dropdown list, the respective Account Name will be saved in currentAccount property of the conditional component. Since currentAccount is the Reactive property by default, the value of the currentAccount will be updated on conditional.html file and passed to the selectedAccount property of all the Child Components. As soon as the selectedAccount of child components is updated, Getter showCard will refresh for all the child components. Only one component that has the account.Name equals to the selectedAccount will return true and will be rendered on UI. The rest of the child components will return false and stays hidden.

This is how we can use Child Components to use template if:true in LWC with Conditional Statements.

That is all from this implementation. If you don’t want to miss the new implementation, please Subscribe here.

If you have any questions about this implementation, please let me know in the comments section below. See you in the next implementation.

Leave a Comment