Hi Folks, In this blog we will try to understand how we can pass data from Parent Component to child Component in LWC.
To enable communication from a parent component to a child component, the child exposes a property or function to make it public.
The @api decorator in the child component exposes a property or function.
Then the parent can update the child’s public property or call the child’s public function.
parent.html
<template>
<lightning-card title="Parent to Child Communication">
<lightning-button label="-" onclick={handleDecrement}>
</lightning-button>
<c-child_event counter={count}></c-child_event>
<lightning-button label="+" onclick={handleIncrement}>
</lightning-button>
</lightning-card>
</template>
parent.js
import { LightningElement } from 'lwc';
export default class Parent_event extends LightningElement {
count=0;
handleDecrement(){
this.count=this.count-1;
}
handleIncrement(){
this.count=this.count+1;
}
}
parent.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
child_event.html
<template>
{counter}
</template>
child_event.js
import { LightningElement,api } from 'lwc';
export default class Child_event extends LightningElement {
@api counter;
}
child_event.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>
If you have any comments or queries about this, please feel free to mention them in the comments section below.
No comments:
Post a Comment