Sub topic 6
Listening in the parent template
This chapter assumes you can write an LWC with @api properties and place one component inside another's template. It also assumes the child already dispatches a CustomEvent named productselected, as covered in the previous chapters. Here the focus is the receiving side: how a parent subscribes to that event in its template, what the handler receives, and what usually goes wrong.
The working model
A parent listens to a child by putting an event handler attribute on the child's tag in the parent's template. The attribute name is the word on followed by the event name. The value is a reference to a method on the parent's class, inside curly braces.
<!-- productList.html -->
<template>
<c-product-tile
product-id="p1"
name="Desk"
onproductselected={handleProductSelected}>
</c-product-tile>
<p>Selected: {selectedId}</p>
</template>// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
selectedId;
handleProductSelected(event) {
this.selectedId = event.detail.productId;
}
}When the child calls this.dispatchEvent(new CustomEvent('productselected', ...)), the event fires on the child's host element. The listener registered by onproductselected is attached to that same element, so the browser calls handleProductSelected with the event object. The assignment to selectedId re-renders the template, and the paragraph updates.
Three facts from this flow are worth keeping in mind:
- The handler runs synchronously.
dispatchEventdoes not return until every listener has finished. - Rendering is not synchronous. The re-render happens after your handler returns, once LWC processes the changed field.
- The parent never reaches into the child. It only reacts to a signal the child chose to send.
Anatomy of the handler attribute
Take onproductselected={handleProductSelected} apart:
| Part | Meaning |
|---|---|
| `on` | Prefix that marks the attribute as an event listener. |
| `productselected` | The exact event name passed to `new CustomEvent(...)`. |
| `{handleProductSelected}` | A reference to a method on the parent class. |
The rules that follow from this:
- The text after
onmust match the event name exactly. The name is lowercase, so the attribute is lowercase. - The braces contain a bare method name. They do not contain a call.
- The method must exist on the parent's class. A missing method is reported as an error when the template is compiled or rendered, not silently ignored.
thisinside the handler is the parent component. You do not needbind.- Each element can have one template handler per event name. To run two pieces of logic, call both from one handler.
Why event names should be lowercase
LWC guidance says a custom event name should use only lowercase letters, with no spaces, hyphens, or uppercase characters. The template attribute is the name with on in front, and HTML attribute names are not a good place for mixed case. If you dispatch productSelected and write onproductSelected in the template, you are relying on case handling that the platform does not promise. Dispatch productselected and write onproductselected. If you need to separate words for readability, prefer a single run of lowercase letters over underscores or hyphens.
Reading the event object
The handler receives a standard DOM Event, more precisely the CustomEvent the child created. The properties you will use most are these:
| Property | What it gives you |
|---|---|
| `event.detail` | The payload the child put in the `detail` option. |
| `event.target` | The element the event was dispatched on, as seen from the parent. For a child's own event this is the child's host element. |
| `event.currentTarget` | The element the listener is attached to. |
| `event.type` | The event name, for example `productselected`. |
| `event.stopPropagation()` | Stops the event from travelling to further ancestors. |
event.detail is whatever the child passed. If the child dispatched with no detail, it is null, and reading event.detail.productId throws a TypeError. When the payload contract is not guaranteed, read defensively:
handleProductSelected(event) {
const productId = event.detail?.productId;
if (!productId) {
return;
}
this.selectedId = productId;
}Because the handler receives the very object the child created, treat detail as read-only. If the child sent an object it also keeps in its own state, a mutation in the parent changes the child's data too. The best-practices chapter returns to this, but the parent-side habit is simple: copy before you change.
Several children, one handler
A parent often renders a list of children and wants one handler for all of them. Put the handler attribute on the element inside the for:each loop. The key attribute is required on the repeated element.
<!-- productList.html -->
<template>
<ul>
<template for:each={products} for:item="product">
<li key={product.id}>
<c-product-tile
product-id={product.id}
name={product.name}
onproductselected={handleProductSelected}>
</c-product-tile>
</li>
</template>
</ul>
<p>Selected: {selectedName}</p>
</template>// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
products = [
{ id: 'p1', name: 'Desk' },
{ id: 'p2', name: 'Chair' },
{ id: 'p3', name: 'Lamp' }
];
selectedName = 'none';
handleProductSelected(event) {
const id = event.detail.productId;
const match = this.products.find((p) => p.id === id);
this.selectedName = match ? match.name : 'none';
}
}The child's detail carries the identity, so the parent does not need to know which instance fired. This is the main reason to put an identifier in the payload. Without it, the parent would have to inspect event.target and read data off the element, which couples it to the child's markup.
Passing context through data attributes
Sometimes the identity is known only to the parent, for example the index of a row. The template cannot pass arguments in onproductselected={handleProductSelected}. Instead, put a data- attribute on the element and read it from event.currentTarget.dataset.
<c-product-tile
key={product.id}
data-row={product.rowNumber}
name={product.name}
onproductselected={handleProductSelected}>
</c-product-tile>handleProductSelected(event) {
const row = event.currentTarget.dataset.row;
// row is a string; convert it if you need a number
console.log(Number(row));
}Use currentTarget here, not target. The dataset is on the element that carries the listener. For an event on a child's host element the two usually match, but after bubbling through wrappers they do not.
Listening on a wrapper element
A handler can be placed on an ancestor of the child inside the same template, such as a div. It only receives the event if the child dispatched it with bubbles: true. Without that, the event is dispatched on the child's host element and goes no further.
<div onproductselected={handleProductSelected}>
<c-product-tile product-id="p1" name="Desk"></c-product-tile>
</div>With the default settings, the handler on the div never runs. Attach it to the c-product-tile tag, or make the child dispatch a bubbling event. The propagation chapter covers bubbles and composed in detail. For now, remember that the safest listening spot is the child's own tag.
Common errors
Calling the method instead of referencing it
<!-- Wrong: invalid in LWC templates -->
<c-product-tile onproductselected={handleProductSelected(product.id)}></c-product-tile>Template expressions in LWC are property references, not JavaScript expressions. You cannot call functions or pass arguments there. Use a data- attribute or a detail payload.
Event name mismatch
The most common cause of "my handler never runs" is a spelling difference between the dispatch and the attribute.
| Child dispatches | Parent writes | Result |
|---|---|---|
| `productselected` | `onproductselected` | Works. |
| `productselected` | `onproduct-selected` | Never fires. |
| `product-selected` | `onproduct-selected` | Not recommended. It breaks the naming rules. |
| `productSelected` | `onproductselected` | Never fires, because event names are case-sensitive. |
When debugging, log in both places. A console.log in the child before dispatchEvent and one in the handler tells you quickly which side is wrong.
Wrong element
Listening on a component that is not the dispatcher is the second most frequent mistake. Suppose c-product-list contains c-product-tile, and c-app contains c-product-list. An onproductselected on <c-product-list> in c-app does not hear the tile's event. The tile dispatched on itself and the event did not bubble. Either the list re-dispatches its own event, or the tile uses bubbling and composing, which has costs.
Reading the wrong property
Reading event.productId instead of event.detail.productId gives undefined with no error. Everything the child sends lives under detail.
Assuming the handler can stop the child
A parent handler cannot return a value to the child. Returning false or calling preventDefault() only matters if the child created the event with cancelable: true and then checks event.defaultPrevented after dispatching. Most events do not use this, so treat events as one-way notifications.
When a template handler is not enough
The template attribute works whenever the child's tag is in the parent's template and always present. If the child is created conditionally, or you need to add the listener at runtime, you can use addEventListener from JavaScript. The next chapter covers that approach. In most components, the template handler is shorter, cannot leak a listener, and is the one to prefer.
Summary of the parent-side checklist
- Choose the lowercase event name the child dispatches.
- Add
on<eventname>={methodName}to the child's tag. - Define
methodName(event)on the parent class. - Read
event.detail, defensively if the contract is loose. - Assign to a field to update the UI.
Exercise
A child dispatches new CustomEvent('itemremoved', { detail: { id: 7 } }). The parent template contains <c-item-row onitemRemoved={handleRemoved}></c-item-row> and the handler never runs. Name two things you would change, and state what the handler should read to get the id.
Show answer
First, the attribute must match the lowercase event name exactly, so write onitemremoved={handleRemoved}. Second, confirm that handleRemoved is defined as a method on the parent class and is referenced without parentheses or arguments. Inside the handler, read the id with event.detail.id. Reading event.id returns undefined, because the payload lives under detail.
Exercise
You render ten c-product-tile elements in a for:each loop. Each needs to report which row was clicked, but the child's event has no payload. How can the parent's single handler find out which row fired, and which event property should it use to read the data?
Show answer
Put a data-row={product.rowNumber} attribute on each c-product-tile and register onproductselected={handleProductSelected} on the same tag. In the handler, read event.currentTarget.dataset.row. Use currentTarget because it is the element that carries the listener and the data- attribute. The value is a string, so convert it with Number(...) if needed. A better design is for the child to include its id in detail.