Sub topic 3
Validating Input with `@api` Getters and Setters
Assume you know JavaScript classes, object references, and the HTML, JavaScript, and metadata files in an LWC. A getter reads a value. A setter receives a new value. In Lightning Web Components, decorating one accessor with @api exposes the property to a parent.
Validating input with `@api` getters and setters
Use a private field to store a normalized value. The setter validates or transforms incoming data. Decorate only the getter or only the setter in the pair.
import { LightningElement, api } from 'lwc';
export default class PriceTag extends LightningElement {
_amount = 0;
@api
get amount() {
return this._amount;
}
set amount(value) {
const number = Number(value);
this._amount = Number.isFinite(number) && number >= 0 ? number : 0;
}
get formatted() {
return `$${this._amount.toFixed(2)}`;
}
}A parent can provide amount as an attribute:
<template>
<c-price-tag amount="19.99"></c-price-tag>
</template>The setter receives the attribute value and converts it to a non-negative number. The child template can read formatted.
Exposing methods with `@api`
A public method gives a parent an imperative action to call. Decorate the method with @api.
import { LightningElement, api } from 'lwc';
export default class SearchBox extends LightningElement {
@api
focusInput() {
const input = this.template.querySelector('input');
if (input) {
input.focus();
}
}
}The parent finds the child in its own template and calls the method. Use public methods for actions that cannot be expressed as property values.
Choosing the right tool
| Requirement | Recommended tool |
|---|---|
| Local primitive state | Plain field |
| Nested plain-object changes | Reassignment, or `@track` when needed |
| Parent-provided value | `@api` property |
| Parent-triggered action | `@api` method |
Prefer reassignment for objects and arrays. Use @track when you must observe mutations inside a plain object or array. Use @api only for the child’s public interface.
Common pitfalls and how to avoid them
- Do not change an
@apiproperty directly in the child. Ask the parent to provide the new value through an event. - Do not decorate both the getter and setter.
- Do not assume every nested object is reactive without reassignment or
@track. - Do not use a public method when a property describes stable state.
Exercise
A child needs to accept a string price, reject negative values, and expose the result to its template. Where should conversion happen?
Show answer
In the @api setter. Store the validated number in a private field, then let the getter return that field.