[SalesForce] LWC – Passing value from child component to Parent – Not working

Having trouble in passing the checkbox value selectedCheck from child JS component to parent component. Also, I am a beginner to use Salesforce Lightening Web Components. Hence, requesting support from this global salesforce group.

Child Component:

import { LightningElement, api, track } from 'lwc';
export default class passCheckboxValue extends LightningElement {    
    @api selectedCheck;
    handlerBlock(event){
        this.selectedCheck = event.target.checked;
        console.log('ChildComp Check'+this.selectedCheck)
        const customEventCheck = new CustomEvent("valueCheck", {        
            detail: this.selectedCheck
        });
        this.dispatchEvent(customEventCheck);       
    }  
}

Child html:

<lightning-layout>
            <lightning-layout-item flexibility="auto" padding="around-small">
                <template if:true={hasDefaultValue}>                  
                    <lightning-input data-id="creditId" type="checkbox" label="Select checkbox" 
                        value={selectedCheck} onchange={handlerBlock} unchecked></lightning-input>
                </template>
            </lightning-layout-item>
        </lightning-layout>

Parent Js:

export default class Parentjs extends NavigationMixin(LightningElement) {
selectedCreditCheck = false;
 parenthandlerCheck(event)
    {
        console.log('handlerCheck event');   //Here the value is shown as undefined     
        this.selectedCheck = event.detail.checked;
    }
}

Parent html:

<c-pass-checkbox-value selected-check={selectedCheck} onvalueCheck={parenthandlerCheck}></c-pass-checkbox-value>

In the parent handler, during execution, I get the value of checkbox at parenthandlerCheck event as undefined.

Any help is much appreciated. Thanks in Advance!

Best Answer

You are passing the data in the wrong format.

this.selectedCheck = event.target.checked;
console.log('ChildComp Check'+this.selectedCheck)
const customEventCheck = new CustomEvent("valueCheck", {        
    detail: this.selectedCheck /* here is the problem */
});
this.dispatchEvent(customEventCheck); 

It should be like this

this.selectedCheck = event.target.checked;
console.log('ChildComp Check'+this.selectedCheck)
const customEventCheck = new CustomEvent("valueCheck", {        
    detail: { checked: this.selectedCheck } /* here is the correct format */
});
this.dispatchEvent(customEventCheck); 
Related Topic