Sub topic 10
Exposing Methods with @api
This chapter covers how a Lightning web component exposes methods to its parent, and where that approach fits against the other ways components communicate. It assumes you know the basics of modern JavaScript (classes, import/export, spread syntax), the structure of a Lightning web component (HTML, JS, and meta files), and the difference between primitive values and object references. It also assumes you have read the earlier chapters on @api properties and one-way data flow.
Why a Component Needs Public Methods
Public properties let a parent push data into a child. Some requests are actions instead of data: "move focus to your input," "clear your selection," "validate yourself." A public method lets the parent ask the child to do one of these.
You expose a method by decorating it with @api. The method then becomes part of the component's public API. Any parent that renders the child can find the element and call the method.
Declaring a Public Method
Place @api directly above a method in the child's class.
import { LightningElement, api } from 'lwc';
export default class SearchBox extends LightningElement {
@api
focusInput() {
const input = this.template.querySelector('input');
if (input) {
input.focus();
}
}
}The matching template contains the input:
<template>
<input type="search" placeholder="Search" />
</template>Three details matter here:
- The method runs in the child's context.
thisis the child component, sothis.template.querySelectorsearches the child's own template. - The
if (input)guard handles the case where the template has not rendered the input yet. This can happen if the input is inside anlwc:ifblock that is currently false. - Without
@api,focusInputis a private method. The parent would find no such function on the element and the call would throw aTypeError.
Calling the Method from a Parent
The parent places the child in its template and gives it a way to be found.
<template>
<c-search-box></c-search-box>
<lightning-button label="Focus search" onclick={handleReset}></lightning-button>
</template>In the parent's JavaScript, query the child element and call the method directly.
import { LightningElement } from 'lwc';
export default class SearchPage extends LightningElement {
handleReset() {
const box = this.template.querySelector('c-search-box');
if (box) {
box.focusInput();
}
}
}The selector c-search-box is the child's tag name. The component folder is named searchBox in camelCase, and the tag uses kebab-case with the namespace prefix c-.
The parent looks inside this.template, which is its own template. It can only reach children that it renders itself. It cannot reach into a grandchild, because the child's template is hidden from the parent by the shadow boundary.
Timing: When Is the Method Available?
A parent can only call a method on a child that exists and has been created. Keep these timing rules in mind:
- In the parent's
constructor, the template has not rendered.this.template.querySelectorreturnsnull. - In the parent's
connectedCallback, the parent's template has still not rendered. The child does not exist yet. - In the parent's
renderedCallback, the child elements exist and public methods can be called. - In event handlers that run after the first render (such as a button click), the child exists unless a conditional block has removed it.
A child inside lwc:if may be absent. This is why the examples guard with if (box). A call on null throws a TypeError and stops the handler.
import { LightningElement } from 'lwc';
export default class AutoFocusPage extends LightningElement {
hasFocused = false;
renderedCallback() {
if (this.hasFocused) {
return;
}
const box = this.template.querySelector('c-search-box');
if (box) {
box.focusInput();
this.hasFocused = true;
}
}
}The hasFocused flag matters. renderedCallback runs after every render, so without the flag the component would steal focus each time it rerenders. The field is reactive, but the template does not read it, so changing it does not trigger another render.
Methods That Return Values and Take Arguments
A public method is an ordinary function. It can accept arguments and return a value.
import { LightningElement, api } from 'lwc';
export default class TagList extends LightningElement {
tags = [];
@api
addTag(name) {
const clean = String(name).trim();
if (!clean || this.tags.includes(clean)) {
return false;
}
this.tags = [...this.tags, clean];
return true;
}
@api
getTags() {
return [...this.tags];
}
}Note what the method does:
addTagreassignsthis.tagswith a new array, so the template rerenders without@track. The method is inside the child, so the child is free to change its own private field.addTagreturns a boolean so the caller knows whether the tag was accepted.getTagsreturns a copy. If it returnedthis.tagsitself, the parent would hold a reference to the child's internal array and could mutate it. A copy keeps the child's state private.
A parent can use the return value directly:
import { LightningElement } from 'lwc';
export default class TagPage extends LightningElement {
handleAdd() {
const list = this.template.querySelector('c-tag-list');
if (list && !list.addTag('urgent')) {
console.log('Tag was empty or already present');
}
}
}Methods and Properties Compared
A public method and a public property both appear on the element, but they behave differently.
| Aspect | `@api` property | `@api` method |
|---|---|---|
| Direction | Parent sets a value | Parent triggers an action |
| Usage in a parent template | Set as an attribute: `heading="Notes"` | Not available in markup. Call from JavaScript |
| Reactive | Yes. Changing it rerenders the child if the template reads it | No. A call only runs the function. Rerender happens only if the function changes a field the template reads |
| Returns a value | Reads back the current value | Can return any value |
| Typical use | Configuration and data | Focus, reset, validate, scroll, refresh |
Methods cannot be set from HTML. There is no attribute that calls a method, so a parent must always call it from its JavaScript.
Design Guidance: Prefer Properties and Events
A public method works, but it is an imperative call that couples the parent to the child. Reach for it when the request is an action that has no natural state. Many cases are better handled another way.
| Situation | Better choice |
|---|---|
| Parent wants the child to show different data | `@api` property |
| Parent wants the child to be open or closed | `@api` boolean property, such as `expanded` |
| Child needs to tell the parent something happened | A custom event dispatched by the child |
| Parent needs the child to focus, scroll, or validate right now | `@api` method |
| Two unrelated components need to share state | A shared module or Lightning Message Service |
A rule of thumb: data flows down through properties, and notifications flow up through events. Methods are the exception for one-time commands that do not fit a property. If you find yourself calling a method to set a value, such as setTitle('New'), use an @api property instead.
Gotchas and Edge Cases
Calling the method on the wrong element
this.template.querySelector('c-search-box') returns the first match only. If the parent renders several boxes, use querySelectorAll and loop, or give the target an identifying attribute and select on it.
import { LightningElement } from 'lwc';
export default class MultiSearchPage extends LightningElement {
focusSecond() {
const boxes = this.template.querySelectorAll('c-search-box');
if (boxes.length > 1) {
boxes[1].focusInput();
}
}
}Misspelled method names
The method name is resolved at call time. A typo such as box.focusInpt() is not caught when the component compiles. It fails at runtime with a TypeError: box.focusInpt is not a function. Check names carefully.
Overwriting a method with a property of the same name
A class cannot expose both an @api property and an @api method with the same name. Pick distinct names.
Reading a template that has not rendered
A method that queries its own template, like focusInput, depends on the child having rendered. If a parent calls it too early (for example in the parent's connectedCallback), the child's querySelector returns null. The guard in the method protects the child. The guard in the parent protects against the child not existing at all. You often need both.
Changing an argument you were given
Objects passed to a public method arrive as references. They may also be read-only proxies if they came from a parent's @api or tracked data. Copy before changing.
import { LightningElement, api } from 'lwc';
export default class Normalizer extends LightningElement {
@api
normalize(record) {
// Spread into a new object instead of editing the argument.
return { ...record, name: String(record.name).trim() };
}
}Decorating a getter or setter instead of a method
A public method is a function. A getter and setter pair is a property. If you need to compute a value on request, you can use either an @api getter (read it like box.total) or an @api method (call it like box.getTotal()). Choose the getter when the value feels like state and the method when it does work or takes arguments.
Testing a Public Method
Because the method is part of the public API, test it through the element. With Jest and @lwc/jest-preset, create the component, attach it to the document, and call the method.
import { createElement } from 'lwc';
import TagList from 'c/tagList';
describe('c-tag-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('accepts a new tag and rejects a duplicate', () => {
const element = createElement('c-tag-list', { is: TagList });
document.body.appendChild(element);
expect(element.addTag('urgent')).toBe(true);
expect(element.addTag('urgent')).toBe(false);
expect(element.getTags()).toEqual(['urgent']);
});
});The test calls addTag the way a parent would. It checks the return values and the copy returned by getTags, so it covers the same contract a real parent relies on.
Summary of the Rules
@apion a method makes it callable by a parent that renders the child.- The method runs inside the child, so
thisandthis.templaterefer to the child. - Call public methods from JavaScript only, after the child has rendered, and guard against a missing element.
- A method can take arguments and return values. Return copies of internal state, not the state itself.
- The child may change its own private fields inside a public method. Reassigning a field rerenders the child as usual.
- Prefer
@apiproperties for data and custom events for upward notifications. Use methods for commands such as focus, reset, or validate.
Exercise
A parent calls this.template.querySelector('c-tag-list').getTags() inside its connectedCallback and gets TypeError: Cannot read properties of null. Why does this happen, and where could the call move so that it works?
Show answer
In connectedCallback the parent's template has not rendered yet, so querySelector returns null and the call on null throws. Move the call to renderedCallback (guarded so it does not repeat on every render) or to an event handler that runs after the first render, and check that the element is not null before calling the method.
Exercise
A child exposes @api getItems() { return this.items; }, where items is a private array field. Why is returning this.items a risk, and how do you fix it?
Show answer
The parent receives a reference to the child's internal array and can change it, which breaks the child's control over its own state. Return a copy instead, for example return [...this.items];.
Exercise
You need a parent to tell a child to show the text "Saved" instead of "Draft". Should you add @api setStatus(value) or an @api status property? Explain.
Show answer
Use an @api status property. The request is about data that the child displays, so a property is reactive, can be set from the parent's template, and fits one-way data flow. A method is for one-time commands such as focus or reset.