Sub topic 11
Calling a child's @api methods from the parent
This chapter assumes you can already expose a child property with @api, bind values in a parent template, and read a basic component lifecycle. Properties cover most parent-to-child communication. Sometimes the parent needs the child to do something instead, such as move focus, reset a form, or scroll to a row. A public method handles that case.
Properties describe state, methods trigger actions
A public property tells the child what it should look like. A public method tells the child to do something once. Compare two ways to focus a search input.
With a property, the parent sets a flag such as shouldFocus. The child has to notice the change, act on it, and then reset the flag, or the next request is ignored. With a method, the parent calls focus() and the child focuses its input.
Use a property when the value describes a lasting condition. Use a method when the parent wants a one-time action, or wants a result back from the child.
| Need | Better fit |
|---|---|
| Show a heading in the child | Public property |
| Keep the child in a "disabled" state | Public property |
| Move keyboard focus into the child | Public method |
| Clear the child's internal form fields once | Public method |
| Ask the child whether its input is valid | Public method that returns a value |
Declaring a public method
Decorate a method with @api and it becomes part of the child's public interface. Methods without @api stay private, and the parent cannot call them.
// searchBox.js (child)
import { LightningElement, api } from 'lwc';
export default class SearchBox extends LightningElement {
@api
focus() {
this.template.querySelector('input').focus();
}
}The child needs a template with an input for the method to find.
<!-- searchBox.html (child) -->
<template>
<input type="search" placeholder="Search tasks" />
</template>Inside the child, this.template.querySelector('input') looks only in the child's own shadow tree. The parent never touches the input directly. It only knows the method name, which makes focus() the child's public contract. The child can later change its markup without breaking the parent.
Calling the method from the parent
The parent finds the child element and calls the method on it.
<!-- app.html (parent) -->
<template>
<lightning-button label="Show search" onclick={handleShowSearch}></lightning-button>
<c-search-box></c-search-box>
</template>// app.js (parent)
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
handleShowSearch() {
this.template.querySelector('c-search-box').focus();
}
}The selector uses the kebab-case tag name, c-search-box, the same name you write in markup. The call itself uses the method name exactly as the child declared it, in camelCase.
The sequence below shows what happens when the user clicks the button.
Arguments and return values
A public method can take arguments and return a value, so it works as a small request-response channel.
// taskForm.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskForm extends LightningElement {
@api
validate() {
const inputs = this.template.querySelectorAll('lightning-input');
let allValid = true;
inputs.forEach((input) => {
if (!input.reportValidity()) {
allValid = false;
}
});
return allValid;
}
@api
reset(defaults = {}) {
this.template.querySelectorAll('lightning-input').forEach((input) => {
input.value = defaults[input.name] ?? '';
});
}
}<!-- taskForm.html (child) -->
<template>
<lightning-input name="title" label="Title" required></lightning-input>
<lightning-input name="owner" label="Owner"></lightning-input>
</template>// taskPage.js (parent)
import { LightningElement } from 'lwc';
export default class TaskPage extends LightningElement {
handleSave() {
const form = this.template.querySelector('c-task-form');
if (form.validate()) {
// The data is valid, so continue with the save.
}
}
handleClear() {
this.template.querySelector('c-task-form').reset({ owner: 'Unassigned' });
}
}The parent asks validate() for a Boolean and uses it to decide what to do. The child owns the validation logic and the parent only reads the answer. Here the lightning-input components are also children of c-task-form, and the form talks to them with the same pattern. reportValidity() is a public method on lightning-input.
Arguments follow the same rule as properties. If the parent passes an object or an array, the child receives a read-only view, so it must copy the data before changing it. The previous chapters on one-way data flow explain why.
When the call can fail
Most problems with public methods come from timing or from a wrong reference. Check these first.
The child has not rendered yet
this.template.querySelector('c-search-box') returns null until the parent has rendered. In constructor() and connectedCallback() the template has not been rendered, so a call there throws a TypeError. Call child methods from event handlers or from renderedCallback().
// app.js (parent)
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
hasFocusedOnce = false;
renderedCallback() {
if (!this.hasFocusedOnce) {
this.hasFocusedOnce = true;
this.template.querySelector('c-search-box').focus();
}
}
}The guard flag matters. renderedCallback() runs after every render, so without the flag the parent would steal focus on each update.
The child is rendered conditionally
If the child sits inside lwc:if, it exists only while the condition is true. After you change the condition, the DOM updates on the next render, not instantly. Selecting the child in the same handler that makes it appear returns null.
<!-- app.html (parent) -->
<template>
<lightning-button label="Open" onclick={handleOpen}></lightning-button>
<template lwc:if={isOpen}>
<c-search-box></c-search-box>
</template>
</template>// app.js (parent)
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
isOpen = false;
focusAfterRender = false;
handleOpen() {
this.isOpen = true;
this.focusAfterRender = true;
}
renderedCallback() {
if (this.focusAfterRender) {
this.focusAfterRender = false;
this.template.querySelector('c-search-box').focus();
}
}
}The handler records the intent and renderedCallback() carries it out once the child exists.
The method is missing @api
Without @api, the method is private. The parent's call fails with an error such as focus is not a function, or, when the name matches a native element method, it runs the native method instead of yours. Check the decorator first.
The selector matches the wrong element
querySelector returns the first match. If the parent renders several c-search-box elements, you get only the first one. Use querySelectorAll and loop, or give the target a data-id and select by it.
// taskBoard.js (parent)
focusCard(event) {
const id = event.target.dataset.id;
this.template.querySelector(`c-task-card[data-id="${id}"]`).focus();
}Reaching a child with lwc:ref
Newer API versions let you label an element with lwc:ref and read it from this.refs. This avoids selector strings.
<!-- app.html (parent) -->
<template>
<lightning-button label="Show search" onclick={handleShowSearch}></lightning-button>
<c-search-box lwc:ref="search"></c-search-box>
</template>// app.js (parent)
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
handleShowSearch() {
this.refs.search.focus();
}
}this.refs is filled in after the first render, so the same timing rules apply. It is also limited to elements in the parent's own template. If your org runs an older API version, use querySelector.
Design guidelines
- Keep the method surface small. Every
@apimethod is a promise to every parent that uses the component. - Name methods as verbs:
focus,validate,reset,scrollToRow. Properties are nouns. - Do not return internal objects. Return plain values or copies so the parent cannot alter the child's state by accident.
- Prefer properties when state is enough. A method that only stores a value for later is a property in disguise, and a setter is clearer.
- Do not use methods to push data that the parent could pass through a bound property. The template expresses that relationship more visibly and re-renders on change.
Summary
- Mark a child method with
@apito expose it. Without the decorator it stays private. - The parent calls it on the element found with
this.template.querySelector('c-child-name')orthis.refs. - Methods suit one-time actions and request-response checks. Properties suit lasting state.
- Call child methods only after the parent has rendered, usually from an event handler or
renderedCallback(). - Arguments from the parent are read-only in the child, so copy objects and arrays before changing them.
Exercise
A parent calls this.template.querySelector('c-date-picker').open() inside its own connectedCallback(), and the console shows "Cannot read properties of null". The child declares @api open() { ... } correctly. What is the cause, and how do you fix it?
Show answer
In connectedCallback() the parent's template has not been rendered, so querySelector finds no c-date-picker and returns null. Move the call to a place that runs after rendering. Use an event handler, such as a button click, or renderedCallback() with a guard flag so it runs only once. If the child sits inside lwc:if, set a flag when the condition changes and make the call in renderedCallback() after the child exists.
Exercise
A c-task-form child needs to tell its parent whether all required inputs are filled in before the parent saves. Should you use a public property, a public method, or a slot? Write the method signature the child would expose.
Show answer
Use a public method, because the parent needs an answer at one moment, on demand, and not a lasting state. The child exposes @api validate() { ... }, which returns true when every input passes reportValidity() and false otherwise. The parent calls this.template.querySelector('c-task-form').validate() in its save handler.