Sub topic 11
Calling a child's @api methods from the parent
This chapter assumes you can build a basic Lightning web component and already know how to expose a field with @api and set it from a parent template. Here you will learn how a parent asks a child to do something by calling a public method.
Properties and methods
A public property hands the child a value. Sometimes the parent needs the child to perform an action instead. Examples are moving focus to an input, resetting a form, or starting a refresh. A value is a poor fit for these cases, because you would have to set a flag and make the child watch for it.
A public method solves this. You decorate a method in the child with @api, and the parent calls it like any JavaScript method.
Exposing a method in the child
Put @api directly above the method. Without it, the method is private, and the parent cannot call it.
// searchBox.js (child)
import { LightningElement, api } from 'lwc';
export default class SearchBox extends LightningElement {
@api
focus() {
this.template.querySelector('input').focus();
}
}The method uses this.template.querySelector to find the input inside the child's own template. The parent does not need to know the input exists. It only knows that the child can be focused.
Calling the method from the parent
The parent first finds the child element, then calls the method on it.
// app.js (parent)
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
handleShowSearch() {
this.template.querySelector('c-search-box').focus();
}
}The selector c-search-box is the kebab-case tag of the child, the same name you use in markup. The call goes through this.template, so it only finds components in the parent's own template.
Timing
The parent can only call the method after the child exists in the DOM. In a click handler this is not a problem. In connectedCallback of the parent, the child has not rendered yet, so querySelector returns null and the call throws an error. Move such calls to renderedCallback, or trigger them from a user action.
If the child is inside an if:true or lwc:if block, it exists only while the condition is true. Check the result of querySelector when that is possible.
handleShowSearch() {
const box = this.template.querySelector('c-search-box');
if (box) {
box.focus();
}
}Methods with arguments and return values
A public method can take arguments and return a value, like any method.
// taskList.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskList extends LightningElement {
_tasks = [];
@api
addTask(name) {
this._tasks = [...this._tasks, { id: Date.now(), name }];
return this._tasks.length;
}
}The parent can use the returned count. Remember the one-way data flow rule from earlier chapters. Objects you pass into a method are read-only in the child, so copy them before you change them, as the example does with the spread syntax.
Choosing between a property and a method
| Need | Use |
|---|---|
| Give the child data to display | Public property |
| Tell the child to do something now | Public method |
| Give the child markup to place inside it | Slot |
| Tell the parent something happened | Custom event |
Prefer properties when you can. They keep the parent's code declarative: the template says what the child should show. Methods are imperative, so use them for actions that have no natural value, such as focus().
A method that mostly sets internal state is a sign that you should use a property. A property with a setter often does the same job and updates correctly when the parent's data changes.
Common mistakes
- Forgetting
@apion the method. The call fails with "is not a function". - Calling the method before the child has rendered.
- Using
document.querySelectorinstead ofthis.template.querySelector. The first does not reach into component templates. - Naming a method like a built-in HTML attribute or property. Names such as
focusshadow the element's own method, which is intended in this example, but names such astitleorhiddencause confusing behavior.
Exercise
A parent calls this.template.querySelector('c-task-list').addTask('Review') inside connectedCallback, and it throws an error. What is the cause, and how do you fix it?
Show answer
In connectedCallback the parent's template has not rendered, so querySelector returns null and calling addTask on it fails. Move the call to renderedCallback or to an event handler such as a button click, and check that the element was found before calling the method.