Hi Folks, In this blog we will try to understand how we can pass data from Child LWC to Parent LWC using Custom Event.
Let's start without delay. First of all we will create child LWC component in which we will create an input field and whatever data the user will provide in this field and as soon as user clicks on send data button this input data will go to parent component and we will going to display this message in our parent component.
childComponent.html
To create a custom event in LWC, we will use the CustomEvent() constructor and To dispatch an event, we will call the EventTarget.dispatchEvent() method.
The only required parameter for the CustomEvent() is a string indicating the event type. Set a detail property in the CustomEvent to pass data up to a receiving component. In the event listener's handler function, receiving components access the data in the detail property.
So if you see the below code, When a user enters a value into the input and clicks the send button, the component creates and sends a CustomEvent called passdatatoparentevent. The data detail in the event is this.messageToPass, which is the message that we are passing to the parent component.
childComponent.js
childComponent.js-meta.xml
We must now use an HTML attribute with the syntax oneventtype to listen for events in the parent component. Because our event type is passdatatoparentevent, our listener will be onpassdatatoparentevent.
So here is the html part for the parent Component. If you see in the below we are calling our child component in Parent Component and for listening the event we are using 'on' keyword with our eventtype and to handle this event we have created a function handleReceivedData.
parentComponent.html
parentComponent.js
In parent JS, the default value for the messageReceivedFromChild is 'Waiting'. Once the event received from the child. We are going to handle this event. Here if you see the handler i.e. handleReceivedData once the event received we are passing the event detail value to messageReceivedFromChild.
parentComponent.js-meta-xml
Let's see its demo now:-
We hope that you find this blog helpful, if you still have queries, don’t hesitate to contact us at omsfdc91@gmail.com.
No comments:
Post a Comment