Sub topic 11
Public properties with @api
This chapter assumes you know LWC class fields, template expressions, and how a custom element maps to a component. It covers how a parent passes data down to a child.
Private by default
Every field on an LWC class is private. Code outside the component cannot read or write it. To let a parent set a value, mark the field with the @api decorator. A decorator is an annotation that the LWC compiler reads and rewrites at build time. It is an LWC addition, not a browser feature.
// 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 } })
);
}
}Here label is public and count is private. The compiler turns label into a property on the custom element, so the DOM treats it like any other element property.
Setting the property from a parent
In a parent template, you write the property as an attribute. The component name counterButton becomes the tag c-counter-button.
<!-- parentPanel.html -->
<template>
<c-counter-button label="Increase" oncountchange={handleCountChange}></c-counter-button>
</template>The template compiler sets label as a property on the element. It does not call setAttribute. A public property is also reactive. When the parent assigns a new value, the child re-renders.
Names are converted between two styles. A property declared as maxCount is written max-count in markup, because HTML attributes are case-insensitive.
Common errors
- Changing a value the parent owns. A child should treat its
@apiproperties as read-only inputs. If a parent passes an object, LWC wraps it so the child cannot mutate it. To change the data, dispatch an event and let the parent update it. - Forgetting the kebab-case conversion. Writing
maxCount="5"in a template does not match the propertymaxCount. Writemax-count="5". - Expecting a private field to be settable. Without
@api, a parent's attribute has no effect on the field. - Putting
@apion both a getter and its setter. Decorate only the first one in the class. The decorator covers the pair.
If you need to validate or transform an incoming value, use a getter and setter pair:
import { LightningElement, api } from 'lwc';
export default class StepLabel extends LightningElement {
_text = '';
@api
get text() {
return this._text;
}
set text(value) {
this._text = (value ?? '').trim();
}
}Exercise
A child component declares @api itemCount = 0;. How should a parent template set it to 5, and why would the child's own code be wrong to run this.itemCount = 10 in response to a click?
Show answer
The parent writes <c-child item-count="5"></c-child>, using kebab-case for the camelCase property. The parent owns the value, so the child should not reassign it. The child should dispatch a CustomEvent and let the parent update the property.