Chapter 27: Child to Parent Communication using Events in LWC

In this chapter, we will learn about Child to Parent Communication in Lightning Web Component.

Topics Covered:

  • What are Events
  • Difference between events in Aura vs LWC
  • Create Event
  • Dispatch Event
  • Attach an Event Listener declaratively and programmatically  (Focus of this chapter is how to attach event Listener declaratively)
  • Handle the event
  • Use Case

Let’s get started …

What are Events? 

Events are actions that happen in the system we are programming — the system produces a signal when an event occurs, and provides a mechanism by which action can be automatically taken when the event occurs.

For example in an airport when the runway is clear for a plane to take off, a signal is communicated to the pilot, and as a result, they commence piloting the plane.

Passing Data Up: Child to Parent Communication

Data must be passed up using Events. Events are just standard JavaScript events that we fire from the child component and listen into the parent.

Note: To communicate down the component containment hierarchy, we can pass properties to the child via HTML attributes, or public methods. To communicate down the component hierarchy we don’t need events.

To communicate between two different components that do not have any direct relation, we use publish-subscribe utility.

Difference between event in Aura VS LWC

Unlike component or application events in Aura , LWC uses Standard DOM events.

In Aura component, we need to create a separate event file and need to register the event, where event is fired.

Moreover, to handle the event, a handler is needed in component hierarchy. In LWC, registering of event is not required.

Step 1: Create an Event

Create Event : We can use the customEvent() constructor to create an event. In constructor we need to pass custom event name and detail of the event. The only difference between event and customEvent() is that the CustomEvent class will allow us to store information in its detail property and thus transmit that information to the listeners of the event.

The customEvent constructor has one required parameter, which is a string indicating the event name. As a component author, we can name the event when we create the event. We can use any string as our event name.

However, recommendation is to follow DOM event standard.

  • No uppercase letters
  • No spaces
  • Use underscores to separate words

Don’t prefix event name with the string on.

new customEvent(eventName, props);

So why do we need Custom events ?

To communicate up the component hierarchy.

From LWC documentation –

WARNING : The CustomEvent interface imposes no type requirements or structure on the detail property. However it’s important to send only primitive data. JavaScript passes all data types by reference except for primitives. If a component includes an object in its detail property, any listener can mutate that object without the component’s knowledge. This is a bad thing! It’s a best practice either to send only primitives, or to copy data to a new object before adding it to the detail property. Copying the data to a new object ensures that you’re sending only the data you want, and that the receiver can’t mutate your data. 

Step 2: Dispatch an Event

Then, we can make an event target dispatch the created event invoking the dispatchEvent standard method.

this.dispatchEvent(new customEvent(eventName, props);

Step 3 Handle an Event :

There are two ways to listen to an event.

  • Declaratively from the component’s HTML template
  • Programmatically using an imperative JavaScript API

It’s better to listen from the HTML template since it reduces the amount of code we need to write. To handle events, define methods in the component’s JavaScript class

Attach an Event Listener Declaratively

Declare the listener in html of parent component
 parent.html
 <template>
          <c-child-component oneventName={listenerHandler}></c-child-component >
 </template>

Define the handler function listenerHandler,  JavaScript file.

parent.js

import { LightningElement } from 'lwc';
export default class Parent extends LightningElement {
    listenerHandler(){
        // Code runs when event is received
    }
}

Attach an Event Listener Programmatically

we will discuss in detail in next chapter

import { LightningElement } from 'lwc';
export default class Parent extends LightningElement {
  constructor() {
    super();
    this.template.addEventListener('listenerHandler', this.handleListener);
  }
  handleListener = () => {};
}

Use Case 

This is an example of how to create and fire an event declaratively:

child.html

<template>
        <div class="slds-m-around_medium">
<!-- Create child component component from where we will raise a
 event-->
            <lightning-input  
            label="Enter Name" 
            onchange={handleChange}>
          </lightning-input>
     </div>

</template>

child.js

Step1 – Create event- new customEvent(eventName, props);

Step 2 – dispatch event- this.dispatchEvent(new customEvent(eventName, props);

import { LightningElement } from 'lwc';

export default class child extends LightningElement {

   handleChange(event) {
        const name = event.target.value;
        const selectEvent = new CustomEvent('myfirstcustomevent', {
            detail: name
        });
       this.dispatchEvent(selectEvent);
    }
}

parent.html

Step 3: Declare the listener in html of parent component – Declarative via html markup- We need to add prefix as “on” before the custom event name.

in parent component we need to invoke the event listener as handleCustomEvent using onmycustomevent attribute.

<template>
  <lightning-card title="Child Component">
    <div class="slds-m-around_medium">
        <c-child onmyfirstcustomevent={handleCustomEvent}></c-child>
         Value From Child :  {greeting}

    </div>
        </lightning-card>
</template>

parent.js

Step 4:  Handle the event – Define the handler function handleCustomEvent in   JavaScript file.

import { LightningElement  } from 'lwc';

export default class app extends LightningElement {
    greeting;

    handleCustomEvent(event) {
        this.greeting = event.detail;

    }
}

Demo

 

 

I hope you enjoyed this chapter !

 

Together we can learn faster !

Join LWC study group on Telegram 

Subscribe to Youtube channel and blog to get latest updates

 

Reference:

Custom Event

Dispatch Event

Call(), Apply(), Bind() methods in Javascript

Difference between window and this

 

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes

2 comments on “Chapter 27: Child to Parent Communication using Events in LWC

Comments are closed.