Hello Friends, In this post, you will learn how to communicate between parent and child component in lwc. so let's get started,

Communication between parent and child component in lightning web component

To implement this example, you have to create two lwc component.

ChildComponent.html

 <template>
<div style="width:100%;padding:1%">
<lightning-input style="width:100%" value={inputText} type="text" onchange={textChangeHandler}
placeholder="type here.."></lightning-input>
</div>
</template>
ChildComponent.js
 import { LightningElement } from 'lwc';
export default class ChildComponent extends LightningElement {
inputText;

textChangeHandler(event) {
this.inputText = event.target.value;
const selectedEvent = new CustomEvent("textchange", {
detail: this.inputText
});
this.dispatchEvent(selectedEvent);
}
}
ChildComponent.js-meta.xml
 <?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
</LightningComponentBundle>
ParentComponent.html
 <template>
<lightning-card title="Communication between Parent and Child in Lightning Web Components" icon-name="action:announcement">
<c-child-component ontextchange={childTextHandler}></c-child-component>
<div style="width:100%;font-size:15px;padding:1px;margin-left:10px;height:20px;">
<h1>{childText}</h1>
</div>
</lightning-card>
</template>
ParentComponent.js
 import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
childText;
childTextHandler(event) {
this.childText = event.detail;
}
}
ParentComponent.js-meta.xml
 <?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__Tab</target>
</targets>
</LightningComponentBundle>

Output:

 

Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.