Child to Parent Communication by simple action

To communicate between Child to Parent component we should first understand the Events.

Lightning web components dispatch standard DOM events. Components can also create and dispatch custom events.

What is an Event?

JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page When the page loads, it is called an event.

  • When the user clicks a button, that clicks to is an event.
  • Other examples include events like pressing any key, focus, blur, closing a window, resizing a window, etc.
  • Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.

Phases of an Event

The standard DOM Events describes 3 phases of event propagation:

  • Capturing phase –In this event goes down to the element.
  • Target phase –In this event reached the target element.
  • Bubbling phase – In this event bubbles up from the element.

Note - Capturing phase is rarely used in real code, but sometimes can be useful. Normally it is invisible to us. The Lightning web component has only two event propagation

bubbles - A Boolean value indicating whether the event bubbles up through the DOM or not. Defaults to false.

composed - A Boolean value indicating whether the event can pass through the shadow boundary. Defaults to false.

Create and Dispatch Events

To create an event, use the CustomEvent() constructor.

  • The CustomEvent() constructor has one required parameter, which is a string indicating the event type.
  • You can use any string as your event type But recommend are
  • No uppercase letters
  • No spaces
  • Use underscores to separate words
  • Don’t prefix your event name with the string on, because inline event handler names must start with the string on
  • To dispatch an event, call the EventTarget.dispatchEvent() method.
  • In LWC EventTarget is this

fig: CustomEvent flow
fig: CustomEvent flow

Child to Parent communication

There are Three kind of child to parent communication

  1. Simple Event
  2. Event With Data
  3. Event Bubbling

Complete demo of the components.

After placing the component on the page, you will see the following output.

fig:  Child to Parent Communication by simple action

In this blog will only talk about Simple Event

  1. Create two LWC components modalParentComponent and modalChildComponent.
  2. Add the code to the corresponding file from the code given below.

modalParentComponent

modalParentComponent.js
import { LightningElement } from 'lwc';

export default class ModalParentComponent extends LightningElement {
    showModal = false
    showHandler() {
        this.showModal = true
    }
    modalCloseHandler(){
        this.showModal = false
    }
}
modalParentComponent.html
<template>
    <lightning-card title="Simple Event" icon-name="custom:custom14">
        <div class="slds-var-m-around_medium">
            <button class="slds-button slds-button_success" onclick={showHandler}>Open Modal</button>
            <template if:true={showModal}>
                <c-modal-child-component
                header-text="Message!!"
                body-text="This Modal is a Child Component. Triggered from parent and on click of close button it will dispatch an event to parent handler"
                onclose={modalCloseHandler}
                ></c-modal-child-component>
            </template>
        </div>
    </lightning-card>
</template>
modalParentComponent.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
  1. In the parent component,modalParentComponent.html we have created a lightning-card to give our component better looks and feel
  2. Withing thelightning-card we have created a button with an event attribute onclick that will trigger the showHandler handler on click of the button
  3. Below button we are calling the child component using c-modal-child-component.
  4. In modalParentComponent .js file, we have created a showHandler handler in which we are changing the showModal property value from false to true.
  5. By default c-modal-child-component component is hidden because showModal property is false
  6. On click of button showModal property become true and c-modal-child-component component become visible

modalChildComponent

modalChildComponent.js
import { LightningElement, api } from 'lwc';

export default class ModalChildComponent extends LightningElement {
    @api headerText
    @api bodyText
    closeHandler(){
        this.dispatchEvent(new CustomEvent('close'))
    }
}
modalChildComponent.html
<template>
    <div id="myModal" class="modal">
        <div class="modal-content">
            <header>
                <strong>{headerText}</strong>
            </header>
            <p>{bodyText}</p>
            <footer class="text-right">
                <button class="btn danger" onclick={closeHandler}>Close</button>
            </footer>
        </div>
    </div>
</template>
modalChildComponent.css
/* The Modal (background) */
.modal {
    display: block; 
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0, 0, 0); /* Fallback color */
    background-color: rgba(0, 0, 0, 0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    width: 80%;
    top: 50%;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
}
.btn {
    border: none;
    color: white;
    padding: 14px 28px;
    font-size: 16px;
    cursor: pointer;
}
.danger {
    background-color: #f44336;
} 
.success{
    background-color: green;
}
.danger:hover {
    background: #da190b;
}
.text-right {
    text-align: right;
}
modalChildComponent.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>
  1. In modalChildComponent we have created two public property headerText and bodyText. Property become public if we decorate it with @api.
  2. In modalChildComponent.html We have close button and on click of close button we are calling closeHandler method.
  3. In closeHandler method we are creating the new custom event close and dispatching it .
  this.dispatchEvent(new CustomEvent('close'))
  1. Once close event get's triggered it gonna catch my the method modalCloseHandler which is map to the c-modal-child-component component onclose attribute.
  2. Once modalCloseHandler get called it makes the showModal property false and hide the c-modal-child-component component

Output

After placing the component on the page, you will see the following output.

fig:  Child to Parent Communication by simple action
Site developed by Nikhil Karkra © 2021 | Icons made by Freepik