0

Hi have a lwc component where i am making a boolean var to true and to false on a button. But while loading the component and without clicking any button template if:false is being rendered. But i dont want to render any template on page load untill i click the button.Below is the component.

sampleFirst.html:

<template>
<p>Welcome!</p>
<template if:true={dupBoolVar}>
    hello in  true
</template>
<template if:false={dupBoolVar}>
    hello in false
</template>
<div>
<lightning-button variant="Brand" label="Make False" class="slds-m-right_medium" onclick={showFalse}> </lightning-button>
<lightning-button variant="Brand" label="Make True" onclick={showTrue}> </lightning-button>
</div>

sampleFirst.js:

    import { LightningElement } from 'lwc';
export default class SampleFirstLwc extends LightningElement {
    dupBoolVar;
    showFalse(event){
        this.dupBoolVar = false;
    }
    showTrue(event){
        this.dupBoolVar = true;
    }
}

Output I am getting when the lwc component loads is:

enter image description here

But my expected output is I don't want "hello in false" to be shown when the component loads. I want only Welcome! text to be shown when the component loads. Please can anyone help me on this.

2 Answers 2

5

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. ~ Salesforce

https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_conditional

What is falsy value?

Eg. it's undefined or null.

https://developer.mozilla.org/en-US/docs/Glossary/Falsy

What does mean for you?

showTrue is undefined at the beginning which is a falsy value.

What can you do?

get isReady() {
    return this.dupBoolVar !== undefined;
}
<template if:true={isReady}>
    <template if:true={dupBoolVar}>
        hello in  true
    </template>
    <template if:false={dupBoolVar}>
        hello in false
    </template>
</template>
0

Since the boolean variable is undefined on load and the Boolean value of undefined is false, you are getting "hello in false" on load.

To rectify this you can do the following :

  1. Have different boolean variables for "hello in true" & "hello in false" sections. Initialize both the booleans as false use template if:true and make the booleans true on button click.

or

  1. Have an enclosing template with a separate boolean, initialized to false. Make this boolean true on both button clicks
<template if:true={showMessage}>
your existing templates here
</template

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .