Sub topic 2
Public Properties in JavaScript with `@api`
Assume you know the basic files in a Lightning web component (LWC), JavaScript classes, and XML syntax. This chapter connects a component's public JavaScript properties to settings in Lightning App Builder.
Public properties with `@api`
A public property is a value that code outside the component can set. In an LWC, the @api decorator marks a property as public. Import it from lwc.
import { LightningElement, api } from 'lwc';
export default class AccountSummaryCard extends LightningElement {
@api recordId;
@api objectApiName;
@api headerText = 'Summary';
@api maxItems = 5;
}recordId and objectApiName receive record-page context. headerText and maxItems are component settings. The metadata file must expose these settings before an administrator can edit them.
Configuring each target
A target is a type of Lightning page where the component can be placed. A targetConfig groups settings for one or more targets.
<targetConfigs>
<targetConfig targets="lightning__AppPage,lightning__HomePage">
<property name="headerText" type="String"
label="Header text" default="Summary" />
</targetConfig>
<targetConfig targets="lightning__RecordPage">
<property name="headerText" type="String"
label="Header text" default="Summary" />
<property name="maxItems" type="Integer"
label="Maximum items" min="1" max="10" default="5" />
</targetConfig>
</targetConfigs>The property name must match an @api property exactly. A target configuration can give different settings to different page types.
Exposing properties in the property panel
When the component is exposed and its target includes the current page type, App Builder reads its targetConfigs. It then shows matching properties in the property panel. The label is the administrator-facing name. The component's JavaScript class still owns the property values at runtime.
Property types and attributes
Use type to control the kind of value. default supplies a value when the administrator has not selected one. required requires a value. min and max constrain numeric values. A datasource creates choices for a String property.
<property name="size" type="String" label="Card size"
datasource="small,medium,large" default="medium" />Exercise
Which JavaScript declaration must match <property name="maxItems" ...>?
Show answer
The component must declare @api maxItems;.