Lightning Web Components:Communication Between Components From Child to Parent using Custom Events

In this post, we are going to discuss about communication between components from child to parent using custom events. Lightning web component uses Dom event to create and dispatch events.

Suppose, I have two components parent and child. First, we need to create event in child component using custom event and then we need to give name to that particular event. While naming the event we need to adhere to Dom event standards.

  1. There should not be any uppercase letter in the event name.
  2. No spaces allowed in the name of event.
  3. Suppose there are more than two words or over more than one word then we need to separate them using underscore.

Then we need to dispatch event using dispatch event method. Further, we need to define the handler of event in parent component. Remember when
defining the handler of event in parent component we need to use on before the event name.So in our case the name of event is button click so in the handler the the name of event would be onbuttonclick and then it can be binded to a JavaScript function which will do the further operations.

Lets implement this. We will create two components : testParent and testChild and follow the above given steps.

testParent.html

<template>
   
<c-test-child my-name = {chilparam} onbuttonclick = {handleClick}> </c-test-child>

</template>

testParent.js

import { LightningElement,track } from 'lwc';

export default class TestParent extends LightningElement {

    @track chilparam = 'second';
    handleClick(event){
        alert('inside handler of parent');
        this.chilparam = 'third';
    }
}

testChild.html

<template>
    <lightning-card>
        <lightning-button label="click me" onclick = {handleMe}></lightning-button>
    </lightning-card>

<lightning-card  title = "Contact Details" icon-name="standard:contact">
    <p>{myName}</p>
</lightning-card>

    </template>

testChild.js

import { LightningElement ,api} from 'lwc';

export default class TestChild extends LightningElement {
    @api myName = 'first';


    handleMe(event){
        const childEvent = new CustomEvent('buttonclick');//Created Event
        this.dispatchEvent(childEvent); // Dispatched the Event

    }
}

If you include the testParent component inside an aura application and load the application you will see “second” inside contact details.

Now if you will click the “click me” button , alert will popup and once alert is closed the value will be changed to value set in the event handler ie “third”.

Custom Events with Parameters

Now suppose along with the event I want to pass parameters also in the child component. For that, We need to use the detail property of a custom event.

We will update the above components. In the child component , We will create two buttons: “Send Parameters” for sending single paramter to parent component and “Send Multple Parameter” for sending multiple paramaters to parent component.

Sending Single Parameter

While sending the single parameter, we need to assing the value to detail property of event and add it alng with the event name at the time of event creation.Further in the parent component handler we can access it using dot notation say using “event.detail”

Sending Multiple Paramters

Suppose We want to pass multiple parameters then how to achieve that? We have to create a json object with key as paramter name and value as value of parameter.And then we need to add that json object along with the event name while creation of event. In the parent component handler , we need to access the paramters similar to the way in which we access json paramters.(ie using dot notation)

Lets see this with implemenation.

childTest.html

<template>
    <lightning-card>
        <lightning-button label="click me" onclick = {handleMe}></lightning-button>
    </lightning-card>
    <lightning-card>
        <lightning-button label = "Send Parameters" onclick= {handleParameterEvent}></lightning-button>
    </lightning-card>
    <lightning-card>
        <lightning-button label = "Send Multple Parameter" onclick= {handlemultiparameterEvent} ></lightning-button> 
     </lightning-card>

<lightning-card  title = "Contact Details" icon-name="standard:contact">
    <p>{myName}</p>
</lightning-card>

    </template>

childTest.js

/* eslint-disable no-alert */
import { LightningElement ,api} from 'lwc';

export default class TestChild extends LightningElement {
    @api myName = 'first';


    handleMe(event){
        const childEvent = new CustomEvent('buttonclick');//Created Event
        this.dispatchEvent(childEvent); // Dispatched the Event

    }
    handleParameterEvent(event){
        const paramEvent = new CustomEvent('sendparam',
            {
                detail : 'fourth'
            });
        this.dispatchEvent(paramEvent);
    }

    handlemultiparameterEvent(event){
        const multiparam = new CustomEvent('multievent',{
            detail:{
                firstparam : 'fifth',
                secondparam: 'sixth'
            }
        });
        this.dispatchEvent(multiparam);
        
    }
}

parentTest.html

<template>
   
    <c-test-child my-name = {chilparam} onbuttonclick = {handleClick} onsendparam = {handleParam} onmultievent = {handlemultiParam}> </c-test-child>
</template>

parentTest.js

import { LightningElement,track } from 'lwc';

export default class TestParent extends LightningElement {

    @track chilparam = 'second';
    handleClick(event){
        alert('inside handler of parent');
        this.chilparam = 'third';
    }

   handleParam(event){
        var eventparameter = event.detail;
        this.chilparam = event.detail;
    }
    handlemultiParam(event){
         this.chilparam = event.detail.firstparam + ' ' + event.detail.secondparam

    } 
}

Now if you will preview the application. Initial value inside contact details would be “second”. There will be two more buttons “Send Parameters” and “Send Multiple Parameters”.

If you will click on Send Parameters , the value inside contact details will be changed to “fourth”.

If you will click on Send Multiple Parameters , the value inside contact details will be changed to “fifth sixth”.

So , we will wrap up this post here . Stay tuned for next posts !

Advertisement