Skip to main content

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:
Source: force-app/main/default/lwc/clock/clock.js:6-9

Calling a Public Method

Access the child component using querySelector and call the method:
Source: 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:
Source: Similar to force-app/main/default/lwc/navigateToRecordHeadlessAction/navigateToRecordHeadlessAction.js:7

Async Public Methods

Public methods can be async for asynchronous operations:
Source: Similar to 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

Accessing Child Components

Using querySelector

Error Handling

Always handle potential errors in public methods: