You need to fire CustomEvent
from child component to communicate to a parent component.
Here we will go through an example of a child component that displays three car company names as a radio button.
When a car company is selected in the child component we will fire a carchange
event from child component with the name selected by the user.
Parent component will listen to this event and display the selected name in parent component.
Example
1) Create an lwc component with name childLwc
2) Create an lwc component with name parentLwc
3) Now if you surface the parent component in lightning experience, it will look like
Explanation
In childLwc
component, when value of car is changed in the radio button,
it calls JavaScript method in controller sendDataToParent
.
This function then dispatches/fires a custom event with name carchange
.
For every custom event, if you are passing data, you need to pass it as a JSON object with detail
attribute.
parentLwc
component, has a listener added for carchange
event.
It is achieved by adding on+eventname attribute while refering child component in html.
In our case it is oncarchange
attribute added at line 5 of parentLwc
component html.
This basically tells "whenever a carchage event is received, call displayValueInParent
method in JavaScript controller.
Finally when displayValueInParent
method is called,
we take value from the event.details
and assigns to valueSentByChild
variable in JavaScript
Things to Note
- This is a very common pattern to pass values from child component to parent component
- Make sure that you are using
detail
attribute while sending data - Make sure that your event name is all small letters. ie
carchange
instead ofcarChange
- Make sure that your listener name is all small letters. ie
oncarchange
instead ofoncarChange
https://openprocessing.org/sketch/1395158
ReplyDelete