Sub topic 11
Public properties with @api
This chapter assumes you know the earlier chapters on custom elements, component bundles, and class field reactivity. You should also be comfortable with JavaScript classes, getters and setters, and the difference between an HTML attribute and a DOM property.
Why components need a public surface
A Lightning web component is a custom element, and every custom element is a JavaScript object. By default, the fields and methods of your class are private. Code outside the component cannot read them or set them. This is useful, because you can change internals without breaking other components.
A reusable component still needs inputs. A button needs a label, and a list needs its items. The @api decorator marks a class field, getter/setter pair, or method as part of the component's public API. A parent can then set or call it.
Declaring a public property
The counterButton component below exposes label. The count field has no decorator, so it stays private.
// counterButton.js
import { LightningElement, api } from 'lwc';
export default class CounterButton extends LightningElement {
@api label = 'Add';
count = 0;
handleClick() {
this.count += 1;
this.dispatchEvent(
new CustomEvent('countchange', { detail: { count: this.count } })
);
}
}A parent sets the property in its template:
<!-- parentPanel.html -->
<template>
<c-counter-button label="Increase" oncountchange={handleCountChange}></c-counter-button>
</template>Public properties are reactive. When the parent changes the value, the child re-renders if the template uses it. You don't need any extra decorator.
Properties, not attributes
The markup label="Increase" looks like an HTML attribute. For a custom element in an LWC template, the framework assigns the value to the JavaScript property label. This matters in three ways:
- Values keep their type. An expression such as
items={rows}passes the actual array, not a string. - Names follow a convention. A property named
maxCountis writtenmax-countin the parent's markup. The compiler converts between the kebab-case form and the camelCase property. - Attribute reflection is limited. Setting a public property does not always create a matching attribute in the DOM. Don't write CSS selectors that depend on one.
This is the standard custom element model. Elements have properties as well as attributes, and @api is the LWC way to declare which properties exist.
One-way data flow
Data goes down through properties and events go up. The child must treat its @api values as read-only.
- Do not reassign a public property inside the child. The parent owns the value and can overwrite your change on the next render.
- Do not mutate an object or array that the parent passed in. LWC hands the child a read-only view of such values, and an attempted mutation throws an error.
- To change data, dispatch an event and let the parent update its own state. The next chapter covers that pattern in more detail.
If the child needs a modified version, copy the value into a private field.
// sortedList.js
import { LightningElement, api } from 'lwc';
export default class SortedList extends LightningElement {
_items = [];
sorted = [];
@api
get items() {
return this._items;
}
set items(value) {
this._items = value;
this.sorted = [...value].sort((a, b) => a.label.localeCompare(b.label));
}
}Spreading value into a new array avoids sorting the parent's data in place, which would fail on the read-only view.
Getters and setters
A plain @api field is enough when you only store the value. Use a getter and setter when you need to validate or transform input, or derive other state from it, as sortedList does above.
Rules to remember:
- Put
@apion either the getter or the setter, never both. Decorating both is a compile error. - Store the value in a private field with a different name. A common convention is a leading underscore, as in
_items. - The setter runs each time the parent assigns a value. Parents may set several properties in any order, so a setter should not assume that other public properties are already set. Logic that needs several inputs belongs in
connectedCallbackor in a getter that reads them when the template renders.
Public methods
@api also works on methods. This lets a parent give the child an instruction that doesn't fit a property, such as moving focus or resetting state.
// counterButton.js (with a public method added)
import { LightningElement, api } from 'lwc';
export default class CounterButton extends LightningElement {
@api label = 'Add';
count = 0;
@api
reset() {
this.count = 0;
}
handleClick() {
this.count += 1;
this.dispatchEvent(
new CustomEvent('countchange', { detail: { count: this.count } })
);
}
}The parent finds the child element and calls the method:
// parentPanel.js
import { LightningElement } from 'lwc';
export default class ParentPanel extends LightningElement {
handleReset() {
this.template.querySelector('c-counter-button').reset();
}
handleCountChange(event) {
console.log('count is now', event.detail.count);
}
}Prefer properties and events for ordinary data flow. Methods suit imperative actions, and overusing them makes components harder to reason about.
Naming rules and common errors
| Mistake | What happens | Fix |
|---|---|---|
| Public property name starts with `on` | Compile error, because `onclick`-style names are reserved for event handlers | Pick a different name, such as `handler` |
| Name starts with `data` or `aria`, or is a global HTML attribute name such as `title` or `slot` | Error or confusing behavior, because it collides with standard attributes | Choose a descriptive, non-colliding name |
| Name has an uppercase first letter or contains an underscore prefix you rely on to be public | Not reachable as expected from markup | Use camelCase, starting lowercase |
| `@api` on both getter and setter | Compile error | Decorate only the first accessor in the class |
| Public boolean that defaults to `true` | The parent cannot turn it off with `flag="false"`, since the string `"false"` is truthy and a bare attribute means `true` | Default public booleans to `false` |
| Child assigns to a public property or mutates a passed object | Value is overwritten by the parent, or an error is thrown | Copy to a private field and dispatch an event |
| Reading a public property in the constructor | Value is not set yet | Read it in `connectedCallback` or later |
Standard behavior versus LWC additions
Custom elements with properties, and parents setting them from JavaScript, are standard browser behavior. The following parts come from LWC:
- The
@apidecorator syntax and its compile-time checks. - Conversion of kebab-case template names to camelCase properties.
- Read-only views of objects passed to a child.
- Reactive re-rendering when a public property changes.
A plain web component would hand-write a getter and setter, call requestUpdate-style code itself, and list observedAttributes if it wanted attribute support. LWC compiles the decorator into that wiring for you.
Exercise
A child component declares @api recordList and its handler runs this.recordList.push(newRecord). The parent passed in an array. What goes wrong, and how should you fix it?
Show answer
The child receives a read-only view of the parent's array, so push throws an error. Even if it worked, the child would be changing data the parent owns. Fix it by copying the array into a private field (for example this.localList = [...this.recordList, newRecord]) or by dispatching a CustomEvent with the new record so the parent updates its own array.
Exercise
Why must a getter/setter pair for a public property carry @api on only one of the two accessors, and why does the setter usually write to a differently named private field?
Show answer
LWC treats the accessor pair as one public property, so decorating both is a compile error. The setter writes to a differently named field, such as _items, because assigning to this.items inside the setter would call the setter again and recurse forever.