Call child LWC component function from parent LWC function
In this post we will see how to fire or invoke function which is in child component when some event occurred on parent component in lwc.
In our project requirements we may get a situation to call Child Lightning web component function from corresponding parent Lwc component when some event occurs like button click.
If we want to call child component function then
- Child LWC component function should be public (decorated with @api).
- On parent function we need to get child component by name(using template.querySelector) and then we should invoke child function (We should give same function name defined in child).
childLwc.js
import { LightningElement, track, api } from 'lwc';
export default class ChildLwc extends LightningElement {
@track checkBoxChecked = false;
@api childFunction(){
console.log("Child LWC Component method invoked");
this.checkBoxChecked = true;
}
}
childLwc.html
<template>
<div class="slds-box">
<p>I am from Child LWC Component</p><br/>
<lightning-input type="checkbox" label="Parent function Invoked"
checked={checkBoxChecked} name="input1"></lightning-input>
</div>
</template>
parentLwc.js
import { LightningElement } from 'lwc';
export default class ParentLwc extends LightningElement {
onButtonClick(){
console.log("Parent LWC component function invoked")
this.template.querySelector("c-child-lwc").childFunction();
}
}
parentLwc.html
<template>
<div class="slds-box">
<p>Parent LWC componenet</p>
<lightning-button variant="brand"
label="Click Me"
onclick={onButtonClick} class="slds-m-left_x-small"></lightning-button>
</div>
<c-child-lwc></c-child-lwc>
</template>
Output:
On console:
you have kept c-child-lwc in query selector - is that the correct way we have to keep or is that the child lwc cmp name?
ReplyDeletethat's the name of child component
DeleteThat is the standard format for calling a child component in parent. For these kind of reasons only lwc follows Camel letters like start with lower case and uppercase for each next word. So by default when you call child component the format will get changed automatically in VS Code.
ReplyDelete