Event Handling in LWC using JS Controller

In this post, we will implement Event Handling in Lightning Web Components using JS Controller. If you want to check how to handle events using Child component tag, please check this post.

There are two ways of Event Handling in Lightning Web Components:

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

This post will look a lot like an earlier post, but there is a significant difference in handling events.

Event should be handled using JS Controller when we need the control over the handler like, when it should be enabled or disabled. But events does not bubble by default when handling with JS Controller. Hence we have to pass bubbles attribute in the payload while firing the event.

Steps to Implement

  1. Create the event using new CustomEvent(eventname, detailPayload). eventname is the name of custom event and detailPayload is JSON that we can pass to send data. Pass bubbles attribute as true in detailPayload.
  2. Use dispatchEvent(eventInstance) to fire the event where eventInstance the instance of custom event created in step 1.
  3. In Constructor of Parent Component JS, add the event listener using addEventListener(eventname, handlerMethod). eventname is the name of event and handleMethod is binding of handler method using bind().
  4. The handler method will be executed once the event is fired form Child component and we can access the payload details passed from child component using event parameter of this action.

Implementation

Parent component has a markup to display Selected Contact. Child component has the list of Contacts. Once the user click on any of Contact name from the list, we will display 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 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 selected Contact and fire the event using dispatchEvent(). We have to pass the name of selected Contact as part of the payload. Make sure to add bubbles attribute as true in 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, bubbles : true});
        this.dispatchEvent(evtSelectContact);
    }
    
}

Add markup to display selected Contact in Parent component.

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.  -->
            <div class="slds-m-top_x-medium slds-p-around_medium">
                <c-child-cmp></c-child-cmp>
            </div>
        
        </div>
    </lightning-card>
</template>

Add the Constructor in Parent component JS Controller and add the event listener. Make sure that the first line of Constructor is super() as it is mandatory. Bind the handler method while adding the event listener.

parentCmp.js

import { LightningElement } from 'lwc';

export default class ParentCmp extends LightningElement {
    strContactName = '';
    selectedContact = 'None';

    // Constructor
    constructor(){
        super();

        // Adding the event listener and binding fetchSelectedContact() with handler.
        this.template.addEventListener('selectcontactevent', this.fetchSelectedContact.bind(this));
    }
    
    // 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 in Lightning Web Components

The output of this implementation will look like:

Event Handling in Lightning Web Components

This is how we can implement Event Handling in Lightning Web Components using JS Controller. If you want to know more about event handling, you can check this official Salesforce developer guide.

If you don’t want to miss new posts, please subscribe.

Thanks !

1 thought on “Event Handling in LWC using JS Controller”

  1. The selectedContact always shows as none and there is no change and I seriously don’t get the difference between bubbles:false and bubbles:true

    Could you please explain the difference

    Reply

Leave a Comment