childMethodCallByParent

Child component method access by parent component in LWC

LWC

We can call child component method from parent component in using querySelector. So first we need to embed child component in parent component html file

Create Child a Component:-

childCompMethod.html

<template>
    <div>
        <p>
        Hi, I am from child component HTML file.
       </p>
        <p>
        <b>Message from parent comp is </b> : {messagefromparent}
       </p>
       <p>
        <b>Name of parent comp is </b>: {parentcompname}
       </p>
    </div>
</template>      

childCompMethod.js

import { LightningElement, api} from 'lwc';

export default class ChildCompMethod extends LightningElement {

    messagefromparent;
    parentcompname;

    @api childMethod(){
        this.messagefromparent='ParentCompMsg';
        this.parentcompname='ParentCompName';
    }
}

Create a Parent Component:-

parentComp.html

<template>
    <div>
        Hi, I am from parent component HTML file.
        <lightning-button variant="brand" label="CallChildCompMethod" onclick={handleButtonClick}>
        </lightning-button>
        <c-child-comp-method></c-child-comp-method>
    </div>
</template>

parentComp.js

import { LightningElement } from 'lwc';

export default class ParentComp extends LightningElement {
  handleButtonClick(){
    this.template.querySelector("c-child-comp-method").childMethod();
  }
}

link

Leave a Reply