Sub topic 8
Adding a Listener with addEventListener
This chapter assumes you can write an LWC component with @api properties, nest one component in another's template, and dispatch a CustomEvent from a child. It covers the case where the on<eventname> template attribute is not enough and you attach the listener in JavaScript.
When a template handler is not enough
Most of the time you listen in the parent template with onproductselected={handleProductSelected}. That attribute is the best default. It is declarative, and LWC attaches and removes the listener for you.
Use addEventListener when:
- The child is created or removed conditionally, and you want to attach the listener from code that runs after it exists.
- You create elements yourself, for example with
lwc:dom="manual"content. - You need to add or remove a listener at a specific moment, such as in
connectedCallbackanddisconnectedCallback.
Listening on a child element
The parent finds the child with this.template.querySelector and calls addEventListener on it. The child only exists in the DOM after the first render, so the lookup belongs in renderedCallback.
// productList.js (programmatic listener)
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
renderedCallback() {
const tile = this.template.querySelector('c-product-tile');
if (tile && !this._listening) {
tile.addEventListener('productselected', (event) => {
console.log(event.detail.productId);
});
this._listening = true;
}
}
}The handler receives the same event object it would get from a template handler. You read the payload from event.detail.
Why the guard matters
renderedCallback runs after every render, not just the first one. Each call that reaches addEventListener with a new arrow function adds another listener. Without the _listening flag, one click could log the same product several times.
flowchart TD
A[renderedCallback runs] --> B{Child found?}
B -- no --> E[Do nothing]
B -- yes --> C{Already listening?}
C -- yes --> E
C -- no --> D[addEventListener and set flag]The diagram block below shows the same flow in the format the platform renders.
A caveat: if the child is removed and a new instance is rendered later, the flag is still true and the new element has no listener. In that case, track the element itself instead of a boolean.
// productList.js (tracks the element, not a boolean)
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
_listenedTile;
renderedCallback() {
const tile = this.template.querySelector('c-product-tile');
if (tile && tile !== this._listenedTile) {
tile.addEventListener('productselected', this.handleSelected);
this._listenedTile = tile;
}
}
handleSelected = (event) => {
console.log(event.detail.productId);
};
}Using a class field arrow function gives you a stable function reference. A stable reference matters because addEventListener ignores a second registration of the same function on the same element, and because removeEventListener needs the same reference to remove it.
Common errors
| Symptom | Likely cause |
|---|---|
| `tile` is `null` | The lookup ran in `connectedCallback`, before the template rendered. Move it to `renderedCallback`. |
| Handler fires several times per click | Listener added on every render with a new function. Add a guard. |
| Handler never fires after the child is re-rendered | A boolean flag outlived the original element. Track the element. |
| `this` is `undefined` in the handler | A regular method was passed without binding. Use an arrow function or a class field arrow function. |
Summary
addEventListeneris the programmatic equivalent ofonproductselected={...}.- Look up the child in
renderedCallback, notconnectedCallback. - Guard against repeated registration, because
renderedCallbackruns after every render. - Use a stable function reference so you can also call
removeEventListener.
Exercise
A parent adds a listener in renderedCallback with tile.addEventListener('productselected', (e) => this.log(e)) and no guard. The parent re-renders three times after the first render. How many times does log run when the child dispatches one event, and what is a fix?
Show answer
It runs four times: one listener from the first render plus one from each of the three re-renders, because each arrow function is a new reference and so none are treated as duplicates. Fix it by tracking whether the element already has a listener (a flag, or storing the element), or by registering a stable class-field function reference, which addEventListener deduplicates.