December 20, 2020

How to pass data from child to parent component using LWC in Salesforce?

Sample Code:

parentLWC.html:
<template>
    <div class="slds-box slds-theme_default"> 
        Value entered in Child LWC is {strOutput}<br/><br/>
        <c-child-l-w-c
            onpass={fetchValue}></c-child-l-w-c>
    </div>
</template>

parentLWC.js:
import { LightningElement } from 'lwc';

export default class ParentLWC extends LightningElement {

    strOutput;

    fetchValue( event ) {

        console.log( 'Value from Child LWC is ' + event.detail );
        this.strOutput = event.detail;

    }

}

parentLWC.js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

childLWC.html:
<template>
    Enter value: <lightning-input 
                    type="text" 
                    value={strInput}
                    onchange={handleChange}></lightning-input> <br>
    <lightning-button 
        variant="brand" 
        label="Pass to Parent" 
        onclick={passToParent}></lightning-button>
</template>

childLWC.js:
import { LightningElement } from 'lwc';

export default class ChildLWC extends LightningElement {

    strInput;

    handleChange( event ) {

        this.strInput = event.target.value;

    }

    passToParent() {

        console.log( 'Input is ' + this.strInput );
        this.dispatchEvent( new CustomEvent( 'pass', {
            detail: this.strInput
        } ) );

    }

}

childLWC.js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>

Output:


No comments:

Post a Comment