How to invoke methods on child components from parent components in LWC

When we break down functionality into a lot of small components and make it modular, there might be a necessity to invoke methods or functions on the child components from the parent components.

When we break down functionality into a lot of small components and make it modular, there might be a necessity to invoke methods or functions on the child components from the parent components.

We will be looking at how to invoke such child methods.

Let us take a sample Lightning Web Component which accepts the user input via an input box and pushes it to the child component. In the child component, am trying to capitalise the input that user provided.

The catch is, the capitalisation happens when the user clicks on the button that’s on the parent component.

Here is the parent component.

<template>
  <c-child-component name={finalName}></c-child-component>
  <lightning-input name="fullName" onchange={handleChange}></lightning-input>
  <lightning-button
    label="Invoke child method"
    onclick={handleInvokeChildMethod}
  ></lightning-button>
</template>
parentComponent.html
import { LightningElement } from "lwc";

export default class ParentComponent extends LightningElement {

  finalName;
  
  handleChange(event) {
    /*
     * accepting the user input 
     */
    let fName = event.target.value;
    
    /* check if the value is not null, if it's not, then assign the
     * value to the property. 
     */ 
    if (fName !== null ? (this.finalName = fName) : "");
  }

  handleInvokeChildMethod() {
      /* get reference to the child component tag name and invoke 
       * the child method name 
       */
    this.template.querySelector("c-child-component").handleCapitalise();
  }
}
parentComponent.js

This is the JS controller file of the child component. This will house the function that gets invoked from the parent component.

import { LightningElement, api } from "lwc";

export default class ChildComponent extends LightningElement {
  //Parent component pushes the value to the prop name
  @api
  name = "Teja"; 

    /* This is the method that I wish to get invoked from the parent, hence I have decorated it with @api */
  @api
  handleCapitalise() {
  
      /* We are capitalising the input that's being pushed by the parent */
    console.log(this.name.toUpperCase());
  }
}
childComponent.js

The approach that we are taking here is pretty much straight forward and lot more in sync with native JavaScript.

It's as simple as getting a reference to the child component custom tag on the parent component and then invoking the method using the dot notation.