In this blog post, we will learn "How to pass data from child component to parent component in lightning web component".
To pass data from child component to parent component we can trigger event from child LWC and handled it parent LWC as shown in below example.
childcompdemo.html
In the child component HTML file, we are firing event based on button click.
<template>
<div>
Hi, I am from child component HTML
file.
<lightning-button label="Click
Me To Fire Event" onclick={handlebuttonclick}></lightning-button>
</div>
</template>
childcompdemo.js
In the child comp js file, we are passing childcompname and childcompdescription property to parent component.
import
{ LightningElement, api } from 'lwc';
export default class Childcompdemo
extends LightningElement {
@api childcompname='Name of comp is childemocomp';
@api childcompdescription='Description of comp is testing';
handlebuttonclick(){
const evt= new
CustomEvent('myfirstevent',
{detail:{childcompname:this.childcompname,childcompdescription:this.childcompdescription}});
this.dispatchEvent(evt);
}
}
parentcompdemo.html
In the parent component HTML file, we are handling the child comp event.
The keyword "on" is appended before the name of the event using which it is fired.
In this example, we have fired the event from the child component using the name "myfirstevent".
<template>
<div>
Hi, I am from parent component HTML
file.
<c-childcompdemo
onmyfirstevent={handlechildevent}></c-childcompdemo>
</div>
</template>
parentcompdemo.js
/*
eslint-disable no-alert */
import { LightningElement } from
'lwc';
export default class
Parentcompdemo extends LightningElement {
handlechildevent(event){
const
childcompname=event.detail.childcompname;
const
childcompdescription=event.detail.childcompdescription;
alert('Event handled in Parent Comp');
alert('child comp name
is:'+childcompname);
alert('child comp description
is:'+childcompdescription);
}
}
lightningapp.app
<aura:application
extends="force:slds">
<c:parentcompdemo></c:parentcompdemo>
</aura:application>
Nice example and explanation. Really like this.
ReplyDeleteHi, can we also use this if we want to get data into parent component from multiple child components?
ReplyDeletePerfect tutorial for beginners and interview purpose.
ReplyDelete