Overview
The@api decorator can expose methods as part of a component’s public API. Public methods allow parent components to call functions on child components, enabling child-to-parent communication patterns.
Public methods are typically used for imperative actions like refreshing data, opening modals, or resetting component state.
Basic Usage
Exposing a Public Method
Mark a method as public using the@api decorator:
force-app/main/default/lwc/clock/clock.js:6-9
Calling a Public Method
Access the child component usingquerySelector and call the method:
force-app/main/default/lwc/apiMethod/apiMethod.js:4-6
Common Use Cases
1. Refresh Component Data
Refresh data displayed in a child component:2. Reset Component State
Reset form or component state to initial values:3. Focus Management
Programmatically set focus on an input element:4. Screen Actions
Implement custom screen actions for Salesforce flows:force-app/main/default/lwc/navigateToRecordHeadlessAction/navigateToRecordHeadlessAction.js:7
Async Public Methods
Public methods can be async for asynchronous operations:force-app/main/default/lwc/dispatchEventHeadlessAction/dispatchEventHeadlessAction.js:6
Best Practices
Use public methods sparingly. Event-based communication is often more maintainable than directly calling child methods.
When to Use Public Methods
- Imperative actions: Refreshing, resetting, focusing
- Screen actions: Flow integration points
- Utility functions: Reusable logic that doesn’t fit event patterns
When to Use Events Instead
- Data flow: Sending data from child to parent
- User interactions: Button clicks, form submissions
- State changes: Notifying parent of internal state changes
