[SalesForce] call Child LWC from Parent LWC through Button

I am trying to call a Child LWC from a Parent LWC through a button, But child component gets displayed along with the parent component.

<template>
<div style="height: 300px;" >
     <div>  
        <c-new-acre-comp></c-new-acre-comp>
        <lightning-button label="New Acre" onclick={handleClick} class="slds-float--right">
        </lightning-button>
    </div>

and passing my component through the query selector in the handleClick method in JS.

this.template.querySelector('c-new-acre-comp').handleValueChange();

Can someone suggest, what I am missing here?

Best Answer

You need to understand how you can Render DOM Elements Conditionally in Lightning Web Component.

To render HTML conditionally, add the if:true|false directive to a nested tag that encloses the conditional content.

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.

In your case, You need to define a boolean property in js file and use <template if:true={showNewAcreComponent}><c-new-acre-comp></c-new-acre-comp></template> to conditionally show and hide in html file.Let's say, you have defined the property with name showNewAcreComponent having default value as false. Whenever value of showNewAcreComponent property defined in js file returns true, the c-new-acre-comp will render on the screen. When showNewAcreComponent returns false, c-new-acre-comp will not render on the screen dynamically.

    <div style="height: 300px;">
        <template if:true={showNewAcreComponent}>
            <c-new-acre-comp></c-new-acre-comp>
        </template>
        <lightning-button label="New Acre" onclick={handleClick} class="slds-float--right">
        </lightning-button>
    </div>

In your js file, we are changing the property value to true:-

showNewAcreComponent = false;
handleClick() {
    this.showNewAcreComponent = true;
}