How do you expose public properties and methods to parent components using the @api decorator?
Answer
Basics: Components are black boxes. Anything not decorated with @api is private. Public properties let a parent configure a child (<c-card title="Hello">), and public methods let a parent command a child (this.refs.card.reset()). Public properties also become configurable in Lightning App Builder when listed in the meta XML.
How it works:
- Child declares
@api title;. In parent HTML camelCaserecordIdbecomes the attributerecord-id. - The parent assigns the value; the child re-renders when the value changes.
- Parent code reaches methods by getting the element via
this.template.querySelector('c-child')(orlwc:refwiththis.refs) and callingel.method(). - For validation or derived behavior, use a getter and setter pair; decorate only the first of the pair with
@api. - For App Builder, add
<property name="title" type="String"/>insidetargetConfigin the meta file.
Advanced / deep dive: Data flows down through properties and up through events, which keeps components predictable. A child that mutates an @api object it received would silently alter the parent's data, so the framework warns or throws; clone before editing. Setters run before connectedCallback for initial values and again on each change, so they must tolerate undefined and run before other properties are available. Public methods are an escape hatch; prefer property-driven design where possible, because methods couple the parent to child internals and break if the child has not rendered yet. Property names cannot start with , or , and cannot be reserved words like or . A boolean property whose default is cannot be turned off through an HTML attribute, because the attribute's presence means true; default booleans to .