Sub topic 3
Dispatching the Event from the Child
This chapter assumes you can write a basic LWC (an HTML template plus a JavaScript class), expose a property with @api, and place one component inside another. You should also know what a CustomEvent is from the previous chapter. Here the focus is the act of dispatching: where the call lives, what triggers it, and what goes wrong.
What dispatching means
Creating a CustomEvent only builds an object. Nothing happens until you pass it to dispatchEvent. This method is inherited from LightningElement, and it fires the event on the component's host element. The host element is the custom element tag that the parent's template renders, such as <c-product-tile>.
Because the event fires on the host element, the parent can listen on that tag. This is how "events up" works. The child never holds a reference to the parent. It announces that something happened, and whoever is listening decides what to do.
The child component
The child has two public properties and one handler. The handler builds the event and dispatches it.
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
handleClick() {
this.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: this.productId }
})
);
}
}The template connects a native click to that method:
<!-- productTile.html -->
<template>
<button onclick={handleClick}>{name}</button>
</template>The flow has three steps:
- The browser fires a native
clickon the button. onclick={handleClick}runs the method.- The method creates a
CustomEventand callsthis.dispatchEvent(...).
Notice that the dispatching call is this.dispatchEvent, not this.template.dispatchEvent. The first targets the host element, which is what the parent sees. The second targets the root of the child's own shadow tree, so the parent's onproductselected attribute on the child tag would never fire.
Dispatch in response to something
Dispatch from a method that runs for a reason: a user action, a finished operation, or a lifecycle hook. Some common triggers:
| Trigger | Typical place to dispatch |
|---|---|
| User clicks or types | Event handler such as `handleClick` |
| Data finishes loading | After an awaited call or in a wire handler |
| Component is ready | `connectedCallback` (use sparingly) |
| Validation changes | Handler for the input's `onchange` |
A dispatch inside connectedCallback runs before the component is attached and rendered, so a parent listening through a template attribute may still receive it, but a listener added in code later may miss it. Prefer dispatching in response to something that happens after rendering.
Common errors
- Dispatching on
this.template. The parent's template handler is attached to the host element, so it does not receive the event. Usethis.dispatchEvent. - Misspelled event name. The handler attribute is
onplus the event name. If the child dispatchesproductSelected, the parent attributeonproductselectedstill has to match the exact lowercase name. Event names must be lowercase, so useproductselected. - Dispatching the same event object twice. Create a new
CustomEventfor each dispatch. Reusing one instance is unreliable. - Missing handler on the parent. Dispatching to nobody throws no error. If nothing happens, check that the parent attribute is spelled correctly and attached to the right element.
- Putting a changing object in
detail. The payload should be a small, plain value. Passing a reference to your component's own state lets the parent mutate it. The next chapters cover payload design.
Checking the result
In the parent, the matching listener looks like this:
<!-- productList.html -->
<template>
<c-product-tile
product-id="p1"
name="Desk"
onproductselected={handleProductSelected}>
</c-product-tile>
<p>Selected: {selectedId}</p>
</template>Click the button and the paragraph should show Selected: p1. If it stays empty, log inside handleClick first. If the log appears, the child works and the issue is in the parent's listener.
Exercise
A child calls this.template.dispatchEvent(new CustomEvent('productselected')) and the parent's onproductselected handler never runs. What is wrong and how do you fix it?
Show answer
this.template is the root of the child's shadow tree, not its host element, so the event never reaches the listener on the <c-product-tile> tag. Call this.dispatchEvent(...) instead, which fires the event on the host element.
Exercise
Name two places in a child component where dispatching is appropriate, and one place where you should be cautious.
Show answer
Appropriate: a user event handler such as handleClick, and after an asynchronous call completes. Be cautious in connectedCallback, because the component is not yet rendered and a listener added later in code may miss the event.