Sub topic 1
Properties Down, Events Up
Prerequisites
This chapter assumes you know basic JavaScript classes, functions, objects, and ES modules. You should also know how an LWC template and JavaScript class work, how @api exposes public properties, and how to place one component inside another.
Properties Down, Events Up
Lightning Web Components (LWC) use a one-way communication model:
- A parent passes data down to a child through public properties.
- A child sends a signal up to its parent by dispatching an event.
For example, a product list can pass a product ID and name to a product tile. When the user clicks the tile, the child can notify the parent that the product was selected.
A custom event is an event that your component defines for a specific application action. CustomEvent is the browser API used to create one.
Creating a CustomEvent
Create the event inside a child method. Give it a name and, when needed, a detail object containing data for the listener.
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
handleClick() {
const event = new CustomEvent('productselected', {
detail: { productId: this.productId }
});
this.dispatchEvent(event);
}
}The detail property carries the event payload. Keep the payload small and use an object when the listener needs named values.
Dispatching the Event from the Child
Connect the method to a native event in the child template:
<!-- productTile.html -->
<template>
<button onclick={handleClick}>{name}</button>
</template>When the user clicks the button, LWC calls handleClick. The child creates productselected and sends it with dispatchEvent().
The parent can listen for this event in its template:
<!-- productList.html -->
<template>
<c-product-tile
product-id="p1"
name="Desk"
onproductselected={handleProductSelected}>
</c-product-tile>
</template>The on prefix converts the event name into a template listener. The parent handler receives the event object and can read its detail property.
handleProductSelected(event) {
console.log(event.detail.productId);
}Exercise
Which expression reads the product ID sent by the child?
Show answer
event.detail.productId