How To Retrieve Javascript Methods From A Child Component Within A Parent Component In LWC

In this article, we’ll explore accessing JavaScript methods defined in a child component from a parent component. For simplicity, we’ll only include JavaScript code here.

First Step

The initial fundamental step involves exposing a public method and decorating it with @api. Public methods form a component’s API, enabling communication down the hierarchy as parent components can invoke JavaScript methods on child components.

The @api decorator serves to specify a public property and a public JavaScript method within a component.

Here’s an example of how to define methods in the child component JavaScript file named myTime.js:

import { LightningElement, api } from 'lwc';

export default class MyTime extends LightningElement {
    timestamp = new Date();

    

    @api
    showTime() {
     
            this.timestamp = new Date();
    }

   
}

The second step

In order to utilize the method mentioned above in the parent JavaScript, it’s necessary to employ the querySelector on the template, as illustrated below (assuming CheckTime.js is located within the Parent Component):

//CheckTime.js — Parent

import { LightningElement, api } from 'lwc';

export default class CheckTime extends LightningElement {
    timestamp = new Date();

    

   handleTime() {
     
            this.template.querySelector('c-my-time').showTime();
    }

   
}