1

I am doing this udemy course for LWC Development and I am stuck on the part for conditional rendering. My goal is that I should be able to show and hide the div with the use if if:true and if:false directives but for some reason, I am not able to do it. I am sharing my html & js code below:

HTML:

    <lightning-input type="checkbox" label="Show Div" onchange={showDivHandler}>
        <template if:true={displayDiv}>
            <div>Hello again</div>
        </template>
        <template if:false={displayDiv}>
            <div>I am not here</div>
        </template>
    </lightning-input>
</template>

JS:

import { LightningElement, track } from 'lwc';
 
 export default class ConditionRenderingExample extends LightningElement {
     @track displayDiv = false;
  
     showDivHandler(event) {
         this.displayDiv = event.target.checked;
     }
 } 

I have tried adding @track in hopes of making the code work. Any explanations behind this would be really helpful as I have been stuck on this for 2 days already. Thank you.

1 Answer 1

0

you are almost there John, the only change you need to do is move the <template> tags outside the <lightning-input type="checkbox">, as follow:

<template>
    <lightning-input type="checkbox" label="Show Div" onchange={showDivHandler}>
    </lightning-input>
    <template if:true={displayDiv}>
        <div>Hello again</div>
    </template>
    <template if:false={displayDiv}>
        <div>I am not here</div>
    </template>
</template>
2
  • thanks!!! Worked like magic!! why is that the case? why do we need to not enclose it within the <lightning-input type="checkbox"> tag? Jun 15, 2022 at 8:36
  • glad it helped! and the reason why is because there are some html elements that are defined as void elements which means: they are elements whose content model never allows it to have contents under any circumstances. you can read more about it here and you will find which elements do/do not support content within their bodies.
    – McCubo
    Jun 15, 2022 at 8:50

You must log in to answer this question.

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