Sub topic 5
Public properties in JavaScript with @api
This chapter covers the JavaScript side of exposing a component. The .js-meta.xml file decides where a component appears in App Builder. The @api decorator decides which values the component accepts from outside. You need both for a configurable component.
This chapter assumes you can:
- Read a basic Lightning web component bundle (HTML template, JavaScript class, metadata file).
- Deploy code to an org with Salesforce CLI.
- Read simple XML.
What @api does
A class field in a Lightning web component is private by default. Nothing outside the component can set it. Adding the @api decorator makes the field public. A decorator is an annotation placed before a field or method that changes how the framework treats it.
A public property is part of the component's contract. Three kinds of callers can use it:
- A parent component, through an attribute in its template.
- The record page, which sets
recordIdandobjectApiNameautomatically. - App Builder, which sets properties that you list in
targetConfigs.
Here is the class from this tutorial's running example:
import { LightningElement, api } from 'lwc';
export default class AccountSummaryCard extends LightningElement {
@api recordId;
@api objectApiName;
@api headerText = 'Summary';
@api maxItems = 5;
}The class has four public properties:
| Property | Set by | Default |
|---|---|---|
| `recordId` | Record page, automatically | `undefined` |
| `objectApiName` | Record page, automatically | `undefined` |
| `headerText` | Admin in the property panel, or a parent | `'Summary'` |
| `maxItems` | Admin in the property panel, or a parent | `5` |
The two record context properties are only filled in on record pages. On an app page or home page they stay undefined. Write the component so it still renders in that case.
Using the properties in the template
Public properties are available in the template the same way private fields are. Curly braces bind them:
<template>
<lightning-card title={headerText} icon-name="standard:account">
<div class="slds-var-p-around_medium">
<p>Record Id: {recordId}</p>
<p>Object: {objectApiName}</p>
<p>Max items: {maxItems}</p>
</div>
</lightning-card>
</template>Public and private fields are reactive. When the value of a field changes and the template uses it, the component re-renders. This also applies to values that App Builder sets after the component loads. For example, an admin edits the header text in the property panel and the card title updates.
How a value reaches the property
The next diagram shows how an admin's choice in App Builder ends up in your class. The name in the XML must match the name in JavaScript exactly, including case.
The framework matches by name. If the XML says headerText and the class declares @api headerText, the value flows through. If the class declares @api header, the property panel still shows the field, but the component never receives the value. Nothing reports an error, so check the names first when a property seems to do nothing.
Naming rules in parent templates
JavaScript property names use camelCase. When a parent component sets them through markup, it uses kebab-case, which is lowercase words separated by hyphens:
<template>
<c-account-summary-card
header-text="Top accounts"
max-items={limit}>
</c-account-summary-card>
</template>headerText becomes header-text, and maxItems becomes max-items. The component name changes in the same way: accountSummaryCard becomes c-account-summary-card.
App Builder uses the camelCase names in the XML file. Only markup written by developers uses kebab-case.
Property types and what arrives
App Builder stores values for the page, and the framework passes them to your property. The type you declare in the property element controls the editor the admin sees and the type the value has when it arrives:
Stringarrives as a string.Integerarrives as a number.Booleanarrives as a boolean.
Treat the value as already converted. Don't call parseInt on an Integer property. Do check for empty values, because an optional property with no default arrives as undefined.
The later chapters on targetConfigs and property types cover the XML attributes in detail. For now, remember that each XML property needs a matching @api field, and that the field's default value is what the component uses until a value is set.
Do not change @api properties inside the component
A public property is owned by whoever sets it. The component can read it but should not assign to it. A parent passes the value down, and the component treats it as read-only.
This pattern keeps the original value and builds a separate working value:
import { LightningElement, api } from 'lwc';
export default class AccountSummaryCard extends LightningElement {
@api recordId;
@api objectApiName;
@api headerText = 'Summary';
@api maxItems = 5;
get visibleLimit() {
const limit = Number(this.maxItems);
return Number.isFinite(limit) && limit > 0 ? limit : 5;
}
}The template then uses {visibleLimit}. The public property stays as the caller set it, and the getter protects the component from bad values.
Validating with a getter and setter
Sometimes you need to run code when a value is set. A setter does this. Decorate only one of the getter and setter with @api, not both. By convention, you put @api on the getter. The setter is still public.
import { LightningElement, api } from 'lwc';
const MIN_ITEMS = 1;
const MAX_ITEMS = 10;
export default class AccountSummaryCard extends LightningElement {
@api recordId;
@api objectApiName;
@api headerText = 'Summary';
_maxItems = 5;
@api
get maxItems() {
return this._maxItems;
}
set maxItems(value) {
const parsed = Number(value);
const valid = Number.isInteger(parsed) && parsed >= MIN_ITEMS && parsed <= MAX_ITEMS;
this._maxItems = valid ? parsed : 5;
}
}The setter clamps nothing and invents nothing. It accepts only whole numbers from 1 to 10, and it falls back to the default for anything else. The private field _maxItems holds the value, and the underscore prefix is a common naming convention for backing fields.
Use this approach for these cases:
- You must validate or normalize incoming values.
- Setting one property should trigger other work, such as reloading data.
- Several public properties depend on each other.
Remember that setters can run before the component is connected to the page. Don't query the DOM in a setter. Use connectedCallback or renderedCallback for work that depends on the rendered elements.
Property rules worth knowing
These rules cause most of the surprises with public properties.
- Boolean defaults. A public boolean property must not default to
true. If it does, a caller cannot turn it off through markup, because writing the attribute without a value meanstrue. Default booleans tofalse. If you need "on by default" behavior, name the property in the negative, for examplehideIcon. - Names to avoid. Don't start a public property name with
data,aria, oron. Don't use names that are global HTML attributes, such astitle,class, orslot. LWC rejects some of these at compile time, and others behave strangely. - Name length of meaning. Choose
headerTextovertext1. Admins see the label, but developers see the property name, and it becomes API once other components depend on it. - Objects and arrays. A parent can pass an object or array through markup, but App Builder cannot. App Builder property types are limited to simple values. Keep App Builder properties simple, and fetch complex data inside the component.
- Private by default. Don't add
@apito everything. Each public property is a promise you have to keep. Use it only for values that callers need to set.
Public methods
@api also works on methods. A public method lets a parent call into the component, for example this.template.querySelector('c-account-summary-card').refresh(). App Builder never calls methods. They matter only for component-to-component use, so the rest of this tutorial focuses on properties.
Record context on record pages
When you place the component on a record page, the page sets recordId and objectApiName for you. You must declare them with @api and use exactly those names. Don't list them in targetConfigs, because admins should not edit them.
A record page also resolves them when you use the component in a different context. A component on a Contact record page receives the contact's ID and Contact as the object name. The component stays generic and can show information about whichever record it sits on. A later chapter covers this in more detail, including how to restrict a component to certain objects.
Checking your properties
You can confirm that your properties work without waiting for a page. Add the component to a page in a sandbox, then change values in the property panel and watch the card. A quick check follows this pattern:
- Deploy the bundle.
- Open a record page in App Builder and drag the component on.
- Change the property values and compare them with what the card shows.
- Save, activate, and open a real record.
If a value never changes, check the property name in the XML against the class. If it changes in App Builder but not on the live page, make sure you saved and activated the page.
Exercise
A developer adds <property name="title" type="String" label="Title" /> to the targetConfig and declares @api headerText; in the class. The admin types a title in the property panel, but the card does not change. What is wrong, and how do you fix it?
Show answer
The property name in the XML (title) does not match the @api field name (headerText). The framework matches by name, so the value is never delivered to headerText. Rename the XML property to headerText or rename the field to match. The name title is also a poor choice for a public property because it is a global HTML attribute.
Exercise
Why should a component copy an @api value into a private field instead of assigning a new value to the @api property?
Show answer
The caller owns the public property. Assigning to it inside the component logs an error when a parent supplied the value, and the parent can overwrite your change on its next render. Keeping a private field or a getter leaves the original value intact and still lets the component use an adjusted one.
Exercise
You need maxItems to accept only whole numbers from 1 to 10 and fall back to 5 otherwise. Which decorator placement is correct: @api on the getter only, on the setter only, or on both?
Show answer
Put @api on only one of them, conventionally the getter. Decorating both is a compile error. The setter is still public when the getter has the decorator.