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>ChildComponent.js
<div style="width:100%;padding:1%">
<lightning-input style="width:100%" value={inputText} type="text" onchange={textChangeHandler}
placeholder="type here.."></lightning-input>
</div>
</template>
import { LightningElement } from 'lwc';ChildComponent.js-meta.xml
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);
}
}
<?xml version="1.0"?>ParentComponent.html
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
</LightningComponentBundle>
<template>ParentComponent.js
<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>
import { LightningElement } from 'lwc';ParentComponent.js-meta.xml
export default class ParentComponent extends LightningElement {
childText;
childTextHandler(event) {
this.childText = event.detail;
}
}
<?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.
0 Comments
Post a Comment