This post explains how to use the child component methods in parent component in lightning web components(lwc)
To expose a public method, decorate it with @api. Public methods are part of a component’s API. To communicate down the containment hierarchy, owner and parent components can call JavaScript methods on child components.
Ex:
ChildInLWC.html
ChildInLWC.js
handleChangeNameToUpperCase method is declared as public with @api decorator so another component can call this method.
ParentInLWC.html
called the child component in parent component <c-child-in-l-w-c></c-child-in-l-w-c>
ParentInLWC.js
Output
To expose a public method, decorate it with @api. Public methods are part of a component’s API. To communicate down the containment hierarchy, owner and parent components can call JavaScript methods on child components.
Ex:
ChildInLWC.html
<template>
{upperCase}
</template>
ChildInLWC.js
import { LightningElement, api } from 'lwc';
export default class ChildInLWC extends LightningElement {
upperCase;
@api
handleChangeNameToUpperCase(name) {
this.upperCase = name.toUpperCase();
}
}
handleChangeNameToUpperCase method is declared as public with @api decorator so another component can call this method.
ParentInLWC.html
<template>
<lightning-card title="Call child methods in Lightning Web Components">
<lightning-input label="Enter Name" value={nameToChange} onchange={handleOnchange} ></lightning-input>
<c-child-in-l-w-c></c-child-in-l-w-c>
</lightning-card>
</template>
called the child component in parent component <c-child-in-l-w-c></c-child-in-l-w-c>
ParentInLWC.js
import { LightningElement } from 'lwc';
export default class ParentInLWC extends LightningElement {
nameToChange;
handleOnchange(event) {
window.console.log('value ===> '+event.target.value);
this.template.querySelector('c-child-in-l-w-c').handleChangeNameToUpperCase(event.target.value);
}
}
ParentInLWC.js.meta-xml<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="parentInLWC">
<apiVersion>47.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output
Hi I am getting the below error
ReplyDeleteNo MODULE named markup://c:childInLWC found : [markup://c:parentInLWC]LightningComponentBundle
Add Child component like this
Deletec-child-in-l-w-c /c-child-in-l-w-c
For more information check below link
https://www.salesforcecodecrack.com/2020/02/how-to-refer-child-components-names-in.html