Add Event Listeners Dynamically on Children
To add an event listener dynamically to a child component, use the lwc:on directive.
Let's say you have a component spreadOnEvent with a child component spreadOnEventChild. You want to pass properties to the child component with an event handler.
The spreadOnEvent component uses lwc:on to attach a handler for a custom event on the child. The child component dispatches events both when it's inserted into the DOM and when a button is clicked, sending messages and updated properties back to the parent. The parent component updates its display based on the detail property that's received from the child component's events.
The child component spreadOnEventChild displays the name and age property values, and a button to dispatch the custom event.
On initial load, the name and age properties display "James Smith" and "40", which are values that are passed down from the parent component. When the button is clicked, the custom event dispatches and sets the values "LWC" and "8" on the child component.