SalesforceBlue

Feel the rhythm of Salesforce

LWC

Send Events to an Enclosing Aura Component From Lightning Web Components

To communicate from child to parent, dispatch an event. Lightning web components fire DOM events.

An enclosing Aura component can listen for these events, just like an enclosing Lightning web component can. The enclosing Aura component can capture the event and handle it.

For example, let’s update the components created in the part – Compose Aura Components from Lightning Web Components

Add the following code in greetingLwc component:

import { LightningElement} from 'lwc';

export default class GreetingLwc extends LightningElement {
    setGreetingMessage(event) {
        this.dispatchEvent(new CustomEvent('greetings', {
            detail: {
                message : 'Hey! Welcome to SalesforceBlue :)'
            }
        }));
    }
}
<template>
    <lightning-card title="LWC">
        <lightning-button variant="brand" label="Click Me" title="Click Me" onclick={setGreetingMessage} slot="actions"></lightning-button>
    </lightning-card>
</template>

Add the following code to myAuraComponent:

<aura:component implements="flexipage:availableForAllPageTypes">
    <aura:attribute name="message" type="String"></aura:attribute>
    <lightning:card title="AURA COMPONENT">
        <p class="slds-p-horizontal_small">
            {!v.message}
        </p>
        <c:greetingLwc ongreetings="{!c.handleGreetings}" />
    </lightning:card>
</aura:component>	
({
    handleGreetings : function(component, event, helper) {
        component.set("v.message", event.getParam('message'));
    }
})

Add the aura component myAuraComponent to an app page if not added earlier and check the output which will appear as below:

Send Events to an Enclosing Aura Component From Lightning Web Components

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


Leave a Reply

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