Sub topic 2
Exposing a child property with @api
This chapter assumes you can build a simple Lightning web component with an HTML template and a JavaScript class. It also assumes you are comfortable with {propertyName} expressions in templates and with modern JavaScript classes and modules. Here you will learn how a child component declares which of its fields a parent may set.
Why a child needs a public property
A component's fields are private by default. A parent that contains <c-task-card> cannot set or read the card's heading field just because the field exists. The child has to opt in. This keeps each component's internals free to change, and it makes the child's public surface easy to find: everything marked @api is the contract with parents.
The @api decorator creates that contract. A decorator is an annotation placed directly above a class member. It tells the LWC framework to treat that member in a special way. On a field, @api means "a parent may set this from its markup."
Marking a field with @api
Here is a child component with two public properties.
// taskCard.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskCard extends LightningElement {
@api heading;
@api priority = 'normal';
}You must import api from 'lwc' next to LightningElement. Without the import, the decorator is undefined and the component does not compile.
The two fields differ in one way. heading has no initial value, so it is undefined until a parent sets it. priority starts as 'normal', so the card is usable even if the parent never mentions it.
The child's template reads public properties the same way it reads private ones.
<!-- taskCard.html (child) -->
<template>
<article>
<h3>{heading}</h3>
<p>Priority: {priority}</p>
</article>
</template>Nothing in the template tells you which fields are public. Only the decorator in the JavaScript file does.
Setting the property from the parent
The parent sets public properties as attributes on the child's tag.
<!-- taskBoard.html (parent) -->
<template>
<c-task-card heading="Write documentation" priority="high"></c-task-card>
<c-task-card heading={nextHeading}></c-task-card>
</template>The first tag uses literal strings. The second uses {nextHeading}, which reads a value from the parent's own class. The second card has no priority attribute, so it keeps its default of 'normal'.
The tag c-task-card is the child's folder name taskCard in the c namespace, written in kebab-case. The next chapter covers that mapping in detail.
The diagram shows what happens for the first card.
What @api changes about a field
Three behaviors follow from the decorator.
- The field becomes reactive. When the value changes, the framework re-renders the child's template. You do not need
@trackfor this.@trackis for watching changes inside objects and arrays, and it is a different tool. - The field can be set from outside. The parent sets it declaratively, as shown above. A parent can also set it in JavaScript on an element it has queried, for example
this.template.querySelector('c-task-card').heading = 'New'. Prefer the template attribute, because it keeps the data flow visible in markup. - The field is part of the component's public contract. Other developers may depend on its name and type. Renaming or removing it later is a breaking change for every parent that uses it.
On the last point, expose only what a parent needs. If a field is only used inside the child, leave it undecorated.
When the value arrives
A public property is not available at every moment of the child's life. Consider this child.
// taskBadge.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskBadge extends LightningElement {
@api label;
constructor() {
super();
console.log('constructor:', this.label); // undefined
}
connectedCallback() {
console.log('connectedCallback:', this.label); // value set by parent
}
}The parent cannot set properties before the child exists, so label is undefined in the constructor. By the time connectedCallback() runs, the framework has assigned the values from the parent's markup. Put any setup that depends on a public property in connectedCallback() or, for derived values, in a getter. Do not put it in the constructor.
Values can also change after the first render. If the parent later changes nextHeading, the framework assigns the new value to the child and the child re-renders. The next chapters cover that flow, so for now it is enough to know it happens automatically.
Defaults and the parent's value
An initializer on an @api field is only a starting value. If the parent supplies an attribute, that value replaces the default. If the parent omits the attribute, the default stays.
A parent cannot pass "nothing" to restore a default. If the parent binds priority={undefined}, the child's priority becomes undefined and the default is gone. When that matters, use a getter and setter that falls back to the default. The setter pattern is covered in a later chapter.
Rules for naming and declaring public properties
The compiler and the platform restrict some names. Avoid these.
| Avoid | Reason |
|---|---|
| Names starting with `on` | They look like event handler attributes, so the compiler rejects them. |
| Names starting with `aria` or `data` | They collide with standard HTML attribute families. |
| `class`, `slot`, `style`, `is`, `part` | They are reserved or already meaningful on every element. |
| A name starting with an uppercase letter | Property names in LWC start with a lowercase letter. |
Two further rules apply to the declaration itself.
- A member can have only one LWC decorator. You cannot combine
@apiand@trackon the same field. - If you write a getter and setter pair, decorate only the first one in the class. Decorating both is a compile error.
A property is an input, not shared state
The child owns the field's definition, but the parent owns the data. Treat every @api property as an input. Do not write code in the child that assigns a new value to this.heading as part of normal work. If the parent later re-renders with its own value, your assignment is overwritten and the two components disagree about what is true.
If the child needs a modified version of what it received, keep a private copy.
// taskCard.js (child, with a derived value)
import { LightningElement, api } from 'lwc';
export default class TaskCard extends LightningElement {
@api heading;
@api priority = 'normal';
get headingLabel() {
return this.heading ? this.heading.toUpperCase() : 'Untitled task';
}
}The getter headingLabel is private. It computes a display value from the public input and leaves heading untouched. The next chapters on one-way data flow explain why this matters, especially for objects and arrays.
Checking your work
When a public property seems to do nothing, check these in order.
- Is
apiimported? Look at the first line of the child's JavaScript file. - Is the decorator directly above the field? A decorator on a different line from the wrong member is a common slip.
- Does the attribute name match? The child's
@api headingmust be set byheading=in the parent. Names with capital letters follow the kebab-case rule from the next chapter. - Is the value read too early? If the value is
undefinedin the constructor, move the code toconnectedCallback(). - Did you deploy both files? A stale child component in an org is a surprisingly common cause.
Summary of the pattern
The workflow has three steps. Declare the field with @api in the child. Reference it in the child's template. Set it from the parent's template. Everything else in this tutorial builds on that pattern: naming rules, dynamic bindings, objects, lists, setters and methods.
Exercise
A child component declares @api priority = 'normal';. A parent renders <c-task-card></c-task-card> with no attributes. What does the child display for priority, and in which lifecycle hook can you first rely on a parent-supplied value?
Show answer
The child displays normal, because the initializer is the starting value and the parent did not override it. A parent-supplied value is first reliable in connectedCallback(). In the constructor the property is still undefined or the default.
Exercise
A developer writes @api @track items = []; in a child and gets a compile error. What is the cause, and which decorator should stay if the parent supplies items?
Show answer
A class member can have only one LWC decorator. Keep @api because the parent sets the field, and remove @track. An @api field is already reactive when it is reassigned, and the child should not mutate it anyway.