Sub topic 7
Exposing public properties with @api
What this chapter assumes
This chapter assumes you know the following:
- Modern JavaScript: classes,
import/export, and spread syntax. - The basic HTML template syntax used in Lightning web components.
- The three files of a component: HTML, JavaScript, and the meta XML file.
- The difference between a primitive value and an object reference.
It also assumes you have read the earlier chapters on reactive fields. A plain class field already triggers a rerender when you reassign it. Here you will see how @api makes a field visible to a parent component, and what that changes.
What `@api` does
By default, every field on a component class is private. Only the component's own class and template can see it. A parent component that wants to pass data in cannot reach those fields.
The @api decorator makes a field public. A public property is part of the component's contract with the outside world. A parent can set it, and the child can read it.
import { LightningElement, api } from 'lwc';
export default class InfoCard extends LightningElement {
@api heading;
@api expanded = false;
}InfoCard now has two public properties:
headinghas no initial value, so it starts asundefined.expandedstarts asfalse.
Public properties are also reactive. If the parent changes heading, the child rerenders when its template reads heading. You do not need @track for this.
Setting public properties from a parent
A parent sets a child's public properties as attributes in its own template.
<template>
<c-info-card heading="Release notes" expanded></c-info-card>
</template>Three details matter here.
- The tag name. The component folder
infoCardin thecnamespace becomes<c-info-card>. Capital letters in the folder name become a hyphen plus a lowercase letter. - Attribute names. A camelCase property is written in kebab-case in HTML. A property named
maxItemsis writtenmax-items. A single-word property likeheadingstays the same. - Boolean attributes. Writing
expandedwith no value sets the property totrue. This is the standard HTML way to write a boolean attribute.
Passing dynamic values
Use curly braces to bind a value from the parent's own fields.
<template>
<c-info-card heading={title} expanded={isOpen}></c-info-card>
</template>import { LightningElement } from 'lwc';
export default class ReleasePage extends LightningElement {
title = 'Release notes';
isOpen = true;
toggle() {
this.isOpen = !this.isOpen;
}
}When toggle runs, the parent reassigns isOpen. The parent rerenders and passes the new value to c-info-card. The child's expanded property changes, and the child rerenders if its template uses it.
Without braces, the attribute is a literal string. expanded="false" would pass the string "false", and a non-empty string is truthy. This is a common source of bugs. To pass a real boolean false, bind a field that holds false, or leave the attribute out.
How a public property rerenders the child
The reactive model is the same as for private fields. The framework tracks which fields a template reads during rendering. When one of those fields changes value, the component is scheduled to rerender.
For a public property, the "change" happens when the parent assigns a new value. The sequence looks like this:
The key point is the direction. Data moves from parent to child. The child receives values but does not send them back through the same property.
Objects and arrays as public properties
Public properties can hold objects and arrays. Here the reference rules from earlier chapters still apply.
If a parent passes an object to a child, the child's property points at the same object. The parent triggers a child update by assigning a new object to the field that is bound to the attribute.
import { LightningElement } from 'lwc';
export default class ProfileHost extends LightningElement {
person = { name: 'Ada', city: 'London' };
rename() {
this.person = { ...this.person, name: 'Grace' };
}
}<template>
<c-profile-view person={person}></c-profile-view>
<lightning-button label="Rename" onclick={rename}></lightning-button>
</template>The spread creates a new object. The parent field changes, the binding passes the new reference, and the child's person property updates.
If the parent instead wrote this.person.name = 'Grace' on an untracked field, the field would not change value. Nothing would tell the framework to pass anything new. The child would not update. The @track decorator in the parent can change this, which a later chapter covers. For passing data to children, reassigning is the simpler habit.
Why a child must not change its own `@api` properties
Inside the child, a public property is read-only from the point of view of the framework. The parent owns the value. If the child assigns to it, the framework can throw an error, or the assignment can be overwritten the next time the parent rerenders. Either way, the child and parent no longer agree on the value.
Here is the wrong pattern.
import { LightningElement, api } from 'lwc';
export default class BadCounter extends LightningElement {
@api count = 0;
increment() {
// Do not do this. The parent owns count.
this.count += 1;
}
}The problem is ownership. Suppose the parent passes count={total}. The child increments its copy. The parent's total is unchanged, so the two now disagree. When the parent next sets the value, the child's change is lost.
LWC follows one-way data flow: data goes down through properties, and events go up. Because the flow is predictable, you can find the source of any value by looking at the parent.
Two correct alternatives
Copy the value into a private field. Use the public property as the starting value only.
import { LightningElement, api } from 'lwc';
export default class GoodCounter extends LightningElement {
@api startAt = 0;
current;
connectedCallback() {
this.current = this.startAt;
}
increment() {
this.current += 1;
}
}Now startAt stays the parent's value, and current is the child's own state. Note that connectedCallback runs once. If the parent changes startAt later, current does not follow. If you need to follow changes, use a setter, which the next chapter covers.
Tell the parent to change it. The child dispatches a custom event. The parent listens and updates its own field. The new value then flows back down through the property.
import { LightningElement, api } from 'lwc';
export default class EventCounter extends LightningElement {
@api count = 0;
increment() {
this.dispatchEvent(
new CustomEvent('change', { detail: this.count + 1 })
);
}
}<template>
<c-event-counter count={total} onchange={handleChange}></c-event-counter>
</template>import { LightningElement } from 'lwc';
export default class CounterHost extends LightningElement {
total = 0;
handleChange(event) {
this.total = event.detail;
}
}The child asks for a change, and the parent decides.
Mutating objects received through `@api`
The read-only rule covers more than reassignment. If a parent passes an object, the child receives a read-only view of it. Changing a property on that object, such as this.person.name = 'x' in the child, is not allowed and raises an error. The same applies to array methods like push on a passed array.
If the child needs to edit the data, it makes a copy first.
import { LightningElement, api } from 'lwc';
export default class ProfileEditor extends LightningElement {
_person;
draft;
@api
get person() {
return this._person;
}
set person(value) {
this._person = value;
this.draft = { ...value };
}
handleNameChange(event) {
this.draft = { ...this.draft, name: event.target.value };
}
}The spread copy is shallow. Nested objects inside person would still be shared read-only references. For deeply nested data, copy the nested parts you intend to edit, or use structuredClone where it is available.
Naming rules for public properties
The framework restricts some names. Keep these rules in mind when you choose a property name.
| Rule | Example | Why |
|---|---|---|
| Do not start with `on` | `onSelect` is invalid | Names starting with `on` are reserved for event handlers |
| Do not start with `data-` | `data-id` is invalid | These are standard HTML data attributes |
| Do not use reserved global HTML attribute names | `title`, `slot` and similar names can clash | They conflict with built-in HTML behavior |
| Use camelCase in JavaScript | `maxItems` | HTML converts it to `max-items` |
Some global HTML attribute names, such as title, are allowed but behave differently from ordinary properties. The platform may reflect them to the host element's attributes. Prefer a more specific name such as cardTitle when you can.
Default values and when they apply
A public property can have a default value, as expanded = false does. The default applies when the component is created. If the parent never sets the property, the default stays.
Be careful with defaults of true for booleans. HTML boolean attributes cannot express "false" by being present. A parent can only turn the value off by binding a field that holds false. For that reason, the usual guideline is to design public boolean properties so that their default is false. Then a parent opts in by writing the bare attribute.
Seeing the property from the child's template
Inside the child's template, a public property is read like any other field.
<template>
<section class="card">
<h2>{heading}</h2>
<template lwc:if={expanded}>
<slot></slot>
</template>
</section>
</template>Two rules apply to the child's code:
- In the child's JavaScript, read it as
this.heading. - In the template, read it as
{heading}with nothis..
Timing: when is the property available?
Public properties are set by the parent before the child's connectedCallback runs when the parent supplies them in its template. The constructor runs earlier, and the properties are not set at that point. Read public properties in connectedCallback or later, not in the constructor.
import { LightningElement, api } from 'lwc';
export default class Timing extends LightningElement {
@api recordLabel;
connectedCallback() {
// recordLabel is set here if the parent supplied it.
console.log(this.recordLabel);
}
}Properties can also change later, so code that depends on them must handle updates and not only the first value.
Summary of the model
@apimakes a field public and reactive.- Parents set public properties through attributes, using kebab-case names.
- Data flows down. The child treats public properties as read-only and sends changes up with events.
- Objects passed in are read-only views. Copy before editing.
- Reassign objects in the parent to pass new data.
Exercise
A child component declares @api count = 0; and has a button handler that runs this.count += 1;. The parent binds count={total}. Explain what is wrong and show one way to fix it.
Show answer
The parent owns the value of a public property, and the child must not assign to it. Doing so can raise an error or be overwritten when the parent next rerenders, so the child and parent disagree about the value. Fix it by having the child dispatch a custom event, for example this.dispatchEvent(new CustomEvent('change', { detail: this.count + 1 })). The parent handles the event and sets this.total = event.detail, and the new value flows back down through count. Another fix is to copy count into a private field such as current in connectedCallback and change only that field.
Exercise
A parent template contains <c-info-card expanded="false"></c-info-card>. Why does the card still appear expanded, and how should the parent pass a real false?
Show answer
Without curly braces, the attribute value is the literal string "false". A non-empty string is truthy, so the child treats it as true. The parent should bind a field that holds a boolean, such as expanded={isOpen} with isOpen = false, or leave the attribute out so the default false applies.