Child to grandparent communication in LWC

I am providing below the snippets of child, parent and grandparent component, where the child is contained inside the parent component, and the parent is contained inside the grandparent component.

Child

<template>
    <a href="#" onclick={handleClick}>
        <lightning-layout vertical-align="center">
            This is some text
        </lightning-layout>
    </a>
</template>

export default class Child extends LightningElement {
    handleClick(event) {
        event.preventDefault();
        this.dispatchEvent(new CustomEvent('notification'), { bubbles: true, composed: true });
    }
}

Parent:

<template>
    <lightning-card title="EventWithData" icon-name="standard:logging">
        <c-child onnotification={handleNotification}></c-child>
    </lightning-card>
</template>

export default class Parent extends LightningElement {
    handleNotification(event) {
        console.log('This is parent');
    }
}

Grandparent:

<template>
    <c-parent onnotification={handleNotification}></c-parent>
</template>

export default class GrandParent extends LightningElement {
    handleNotification(event) {
        console.log('This is grandParent');
    }
}

I am getting the message from the parent component, signifying that the parent component can listen to the child event, but the grandparent can’t listen to the event. Is there something which I am missing?

Please note that I have set the bubbles and composed property of the event as true.

Answer

It works with bubble & composed set to true.

    // Event dispatch on Grand Child

    //Method to show selected tab upon user select
    selectTab(event) {
        event.preventDefault();
        this.dispatchEvent(new CustomEvent('selecttab', {bubbles: true, composed: true, detail :{ selectedIndex: this.tabIdVal}}));
    }

    // Event listener on Grand Parent

    constructor() {
        super();
        this.addEventListener('movetab', this.moveTab.bind(this));
        this.addEventListener('selecttab', this.selectTab.bind(this));      
    }

Attribution
Source : Link , Question Author : snl , Answer Author : Murali

Leave a Comment