Event Handling in LWC (Lightning Web Components)

There are two ways for Event Handling in LWC (Lightning Web Components):

  1. Event Handling using the Child component tag.
  2. Event Handling in JS Controller.

In this post, we will implement the event handling using Child component creation tag.

There are two types of communication in Component hierarchy.

  1. Parent to Child communication where we need to pass some data to child components by calling the method of Child component from the Parent component. You can check this post for the implementation in detail.
  2. Child to Parent communication where we need to call a method of Parent component from Child component. This is done using Event Handling.

For the demonstration, we will use the same code that we used in the implementation of the Calling the Method of Child component from the Parent component. We will modify the code for event handling to call the method of Parent component using Child component.

Steps to Implement

  1. Create the event using new CustomEvent(eventname, detailPayload). eventname is the name of the custom event and detailPayload is JSON that we can pass to send data.
  2. Use dispatchEvent(eventInstance) to fire the event where eventInstance the instance of the custom event created in step 1.
  3. On the Child component tag in Parent Component, handle the event by adding attribute ‘oneventname‘ and assigning the action. Note that, the attribute name should be the concatenation of ‘on’ and ‘eventname’ and eventname should be in lowercase as it is mandatory to have attribute name in lowercase.
  4. The action assigned to the event attribute will be executed once the event is fired from the Child component and we can access the payload details passed from the child component using event parameter of this action.

Implementation

The parent component has a markup to display Selected Contact. The child component has the list of Contacts. Once the user clicks on any of the Contact name from the list, we will display the name of that Contact in Parent Component. This implementation also has the code to add the Contact from Parent component to the list of Contacts in Child component. That code is not explained here. To understand it, you can go through this post, as it explains how to call a method of Child component from the Parent component.

In Child component, add standard onclick event that will call the JS Controller action.

childCmp.html

<template>
    <h1 class="slds-text-heading_small">List of Contacts</h1>
    <div class="slds-p-around_medium">
        <!--For each loop to display Contact from the list.-->
        <template for:each={lstContacts} for:item="contact">
            <p key={contact} onclick={selectContact}>{contact}</p>
        </template>
    </div>
    
</template>

selectContact action will get the name of the selected Contact and fire the event using dispatchEvent(). We have to pass the name of the selected Contact as part of the payload.

childCmp.js

import { LightningElement, track, api } from 'lwc';
export default class ChildCmp extends LightningElement {
    // Default list of Contacts.
    @track lstContacts = ["Weird Coder", "Red Devil", "Mystic Baba", "OneManArmy Baburao"];
    
    // This method will add new Contact into Contact list.
    @api
    addContactToList(strContactName){
        this.lstContacts.push(strContactName);
    }
    // To fire the event after clicking on Contact name from the list.
    selectContact(event){
        const strSelectedContact = event.target.textContent;
        const evtSelectContact = new CustomEvent('selectcontactevent', {detail : strSelectedContact});
        this.dispatchEvent(evtSelectContact);
    }
    
}

In the Parent component, add event attribute onselectcontactevent on Child component tag with action fetchSelectedContact to handle the event. Add markup to display selected Contact.

parentCmp.html

<template>
        
    <lightning-card  title="Niks Developer Account Details">
        <div class="slds-m-bottom_x-large">
    
            <!-- Input for Contact Name -->
            <div class="slds-p-around_medium lgc-bg">
                <lightning-input type="text" label="Contact Name" placeholder="Enter contact name..." value={strContactName} onchange={changeName}></lightning-input>
            </div>
    
            <!-- Button to add contact -->
            <lightning-button variant="brand" label="Add Contact" title="Add Contact" onclick={addContact} class="slds-p-around_medium"></lightning-button>
            <!-- To display the selected Contact.-->
            <div class="slds-m-top_x-medium slds-p-around_medium">
                Selected Contact:  <p style="color:green;display:inline">{selectedContact}</p>
            </div>
            
            <!-- Child Component to display list of Contacts.  -->
            <!-- We have added the attribute onselectcontactevent to listen to the event. -->
            <div class="slds-m-top_x-medium slds-p-around_medium">
                <c-child-cmp onselectcontactevent={fetchSelectedContact}></c-child-cmp>
            </div>
        
        </div>
    </lightning-card>
</template>

parentCmp.js

Finally, add the fetchSelectedContact() in JS Controller to get the name of selected Contact from the detail payload of event parameter and assign it to selectedContact to update it on UI.

import { LightningElement } from 'lwc';
export default class ParentCmp extends LightningElement {
    strContactName = '';
    selectedContact = 'None';
    
    // To call the child component method to add the Contact into the list.
    addContact(event){
        const objChild = this.template.querySelector('c-child-cmp');
        objChild.addContactToList(this.strContactName);
    }
    // To update the Contact name after updating it on UI. 
    changeName(event){
        this.strContactName = event.target.value;
    }
    // To update the selected contact from the event.
    fetchSelectedContact(event){
        this.selectedContact = event.detail;
    }
}

Event Handling using Lightning Web Components

The output for above implementation:

Event Handling using Lightning Web Components
Event Handling in LWC (Lightning Web Components)

This is how we can use Event Handling in LWC (Lightning Web Components).

Also Read:

If you want to know more about Event Handling using Lightning Web Components, you can check the official Salesforce developer guide here.

The next post will be about Event Handling using JS Controller. If you don’t want to miss it, please Subscribe.

See you in the next post.

2 thoughts on “Event Handling in LWC (Lightning Web Components)”

Leave a Comment