Child to parent component communication in lwc

    An application composes multiple lighting web components, and we frequently want those components to share the information. A component inside another component creates the Parent and child relationship. How a parent communicates with a child is different from how a child communicates with its parent.

Sharing information between the LWC components is simple by using the custom events.

There are 3 types of communication,

  1. Child to parent 
  2. Parent to child
  3. Unrelated Components communication

In this section, we will see how to communicate from child to parent.



childLwc.html


<template>
<lightning-input onchange={handleChange} type="number" name="input1"
    label="Enter a number"></lightning-input>
</template>

childLwc.js

In the child component, we will create and dispatch the event by passing the information in the form of the JSON structure.


import { api, LightningElement } from 'lwc';
export default class ChildLwc extends LightningElement {
@api progressValue;
handleChange(event){
this.progressValue = event.target.value;
        // Dispatch the event
const selectedEvent = new CustomEvent("progressvaluechange",{
detail: this.progressValue
});
this.dispatchEvent(selectedEvent);
}
}

parentLwc.html

In the parent component, we will handle the event. 


<template>
<lightning-card title="Getting Data From Child">
<p class="slds-p-horizontal__small">
<lightning-progress-bar value={progressValue} size="large" >
            </lightning-progress-bar>
<c-child-lwc onprogressvaluechange={handleProgressValueChange}></c-child-lwc>
</p>
</lightning-card>
</template>

parentLwc.js


import { LightningElement, track } from 'lwc';

export default class ParentLwc extends LightningElement {
@track progressValue;
    // Handle the custom event
handleProgressValueChange(event){
this.progressValue = event.detail;
}
}






Popular posts from this blog

How to extract information from xml using node.js

How to clone a record using custom button in salesforce