SalesforceBlue

Feel the rhythm of Salesforce

LWC

Communicate With Events In Lightning Web Components

Communicating From Child To Parent In LWC:

A child component can dispatch a custom event which will be handled by the parent component. Let’s understand this by the below example:

In this example, the child component will be sending a message to the parent component.

Create a component(LWC) named as childLwc and insert the following code:

import { LightningElement } from 'lwc';

export default class ChildLwc extends LightningElement {
    childHandler() {
        const evt = new CustomEvent('sendmessage', {detail: "Hey, This message is sent from child Component"});
        this.dispatchEvent(evt);
    }
}

At Line 5 in the above Javascript code, we are creating a custom event by providing the name along with passing data in the event.

const evt = new CustomEvent('sendmessage', {detail: "Hey, This message is sent from child Component"});

At Line 6 we are dispatching the event.

this.dispatchEvent(evt);
<template>
    <lightning-card title="Child LWC">
        <lightning-button variant="brand" label="Send Message" title="Send Message" slot = "actions" onclick={childHandler}></lightning-button>
    </lightning-card>
</template>

Create a component(LWC) named as parentLwc and insert the following code:

<template>
    <lightning-card title="Parent LWC">
        <p class="slds-p-horizontal_small">
            Message : {message}
        </p>
        
        <c-child-lwc onsendmessage={parentHandler}></c-child-lwc>
    </lightning-card>
</template>

In the above HTML code at Line 8, we have added the handler – onsendmessage={parentHandler}. Whenever the child component dispatches the custom event sendmessage, the parent would be handling it.

import { LightningElement } from 'lwc';

export default class ParentLwc extends LightningElement {

    message;

    parentHandler(event) {
        this.message = event.detail;
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
  <apiVersion>55.0</apiVersion>
  <isExposed>true</isExposed>
  <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>

Add the parentLwc component to an App page. You will get an output like below:


Communicating From Parent To Child In LWC:

Decorate a method with @api in the child component to allow a parent component to call methods in the child component. Let’s understand this with the below example.

We would be updating the childLwc and parentLwc components created above for this example.

Add the following code in childLwc component:

import { LightningElement, api } from 'lwc';

export default class ChildLwc extends LightningElement {
    message;

    @api greet(message) {
        // Suppose a translating capability is here which translate the message param to local user's language
        this.message = message;
    }
}

At Line 8 in the above code, we have decorated the greet method with @api so that it is publically available to be called from the parent component.

<template>
    <lightning-card title="Child LWC">
        <p class="slds-p-horizontal_small">
            Message In Child Component : {message}
        </p>
    </lightning-card>
</template>

Add the following code in parentLwc component:

<template>
    <lightning-card title="Parent LWC">
        <lightning-button variant="brand" label="Send Message" title="Send Message" slot = "actions" onclick={parentHandler}></lightning-button>
        <c-child-lwc onsendmessage={parentHandler}></c-child-lwc>
    </lightning-card>
</template>
import { LightningElement } from 'lwc';

export default class ParentLwc extends LightningElement {

    parentHandler(event) {
        this.template.querySelector('c-child-lwc').greet('Hey, This Message Is Sent From Parent!');
    }

}

In the above code, we are calling the child method by using this.template.querySelector(‘c-child-lwc’)

querySelector() returns the first Element within the document that matches the specified selector.

View the parentLwc component on the lightning app page, you would be getting the below output:


Now you know how to communicate between parent to child and vice-versa 🙂

You should be also aware of how to Communicate Across The DOM and Configuring Event Propagation. Please go through them to learn more about communicating with events.

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


2 thoughts on “Communicate With Events In Lightning Web Components

  • Gal Jerman

    Top site ,.. amazaing post ! Just keep the work on !

    Reply
  • My site YV6 covers a lot of topics about Airport Transfer and I thought we could greatly benefit from each other. Awesome posts by the way!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *