Thursday, May 7, 2020

Send Events From LWC to an Enclosing Aura Component


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


This Lightning web component fires a custom statuschange event in its JavaScript file.

// statuschange.js

import { LightningElement } from 'lwc';

export default class statuschange extends LightningElement {

    handleCheckboxChange() {
        // Get the labels of selected checkboxes
        const status= Array.from(
            this.template.querySelectorAll('lightning-input'),
        )
            .filter(element => element.checked)
            .map(element => element.label);
        const statusChangeEvent = new CustomEvent('statuschange', {
            detail: { status},
        });
        // Fire the custom event
        this.dispatchEvent(statusChangeEvent);
    }
}

<!-- statuschange.html -->

<template>
    <lightning-input label="statu 1" type="checkbox" onchange={handleCheckboxChange}></lightning-input>
</template>


The enclosing Aura component wrapper adds a handler for the custom event.


 Notice that the event handler, onstatuschange, matches the event name with “on” prefixed to it.

 That is, use onstatuschange to handle the event named statuschange.

<!-- auraEventListener.cmp -->

<aura:component implements="flexipage:availableForAllPageTypes">
    <aura:attribute name="message" type="String" default="No selection"/>

    <lightning:card title="AuraEventListener" iconName="custom:custom30">

        <aura:set attribute="actions">
            <span class="aura">Aura Component</span>
        </aura:set>
        <div class="slds-m-around_medium">
            <lightning:layout>
                <lightning:layoutItem size="4">
                    <!-- This is an LWC component -->
                    <c:statuschange onstatuschange="{!c.handlestatuschange}"/>
                </lightning:layoutItem>
                <lightning:layoutItem size="8" class="slds-p-left_medium">
                    {!v.message}
                </lightning:layoutItem>
            </lightning:layout>
        </div>
    </lightning:card>
</aura:component>

// auraEventListener.js

({
    handlestatuschange: function(component, event) {
        var status1 = event.getParam('status');
        component.set('v.message', status1.length > 0 ? 'Your selection: ' + status1.join() : 'No selection');
    },
});

No comments: