Hi Folks, In this blog we will try to understand how we can call child LWC methods in parent LWC using querySelector
- The
querySelector()
method is a standard DOM API that returns the first element that matches the selector. - Parent component can invoke a child component’s public method as well, for this to work declare the method as public in child using @api annotation
In this example child LWC exposes
increaseCounter
()
, decreaseCounter
()
, methods by adding the @api
decorator to the methods. A parent component that contains c-child
( i.e. our child LWC) can call these methods.child.html
<template>
<lightning-card title="Child LWC">
<div class="slds-m-around_medium">
{counter}
</div>
</lightning-card>
</template>
child.js
import { LightningElement,api } from 'lwc';
export default class child extends LightningElement {
counter=0 ;
@api increaseCounter(){
this.counter=this.counter+1;
}
@api decreaseCounter() {
this.counter=this.counter-1;
}
}
The parent component contains
c-child
and has buttons to call the increaseCounter
()
and decreaseCounter
()
methods in parent LWC
. Here’s the HTML.parent.html
<template>
<lightning-card title="Parent LWC">
<lightning-button label="Increase Counter" onclick={handleIncrease}> </lightning-button>
<lightning-button label="Decrease Counter" onclick={handleDecrease}> </lightning-button>
<br>
<c-child></c-child>
</lightning-card>
</template>
The handleIncrease() function in parent LWC calls the increaseCounter() method in the c-child element. this.template.querySelector('c-child')
returns the c-child element in parent.html. The this.template.querySelector()
call is useful to get access to a child component so that you can call a method on the component.
The handleDecrease() function in parent LWC calls the decreaseCounter() method in the c-child element.
parent.js
import { LightningElement } from 'lwc';
export default class parent extends NavigationMixin(LightningElement) {
handleIncrease() {
this.template.querySelector('c-child').increaseCounter();
}
handleDecrease() {
this.template.querySelector('c-child').decreaseCounter();
}
}
Output:-
If you have any comments or queries about this, please feel free to mention them in the comments section below.
No comments:
Post a Comment