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.
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.In your js file, we are changing the property value to true:-