Public Properties and Public Methods
By the end of this lesson, you'll be able to:
- Expose a callable public method on a component using @api
- Decide when a public method is more appropriate than a public property
- Call a public method on a child component from its parent
Prerequisites: "Parent-to-Child Communication with @api"
Public Methods with @api
// contactForm.js
import { LightningElement, api } from 'lwc';
export default class ContactForm extends LightningElement {
firstName = '';
lastName = '';
@api
clearForm() {
this.firstName = '';
this.lastName = '';
}
}
@api can decorate a method, not just a property — making it callable directly by a parent holding a reference to this child element.
When to Use a Method vs. a Property
- Public property — passive data the child displays or reacts to (Lesson 1).
- Public method — an action the parent triggers on the child at a specific moment, like "reset now" or "focus this field now."
Calling a Child's Public Method
<!-- parent's template -->
<c-contact-form lwc:ref="form"></c-contact-form>
<lightning-button label="Clear" onclick={handleClear}></lightning-button>
// parent's JS
handleClear() {
this.refs.form.clearForm();
}
lwc:ref gives the parent a direct reference to the child element, so it can call the exposed method. Module 11's "DOM Querying and Refs" lesson covers this mechanism in full depth — this is a first, practical look.
Why This Matters in Real Projects
Real components often need imperative "do this now" actions from a parent — clearing a form after successful submission, refocusing an input after validation fails — that a passive data property alone can't express.
Exercise
Add an @api method named resetSelection to a component that clears a field called selectedId.
Show hint
@api can decorate a method exactly like a property.
Exercise
Challenge: explain, as a comment, why a "clear the form" action is a better fit for a public method than a public property.
Show hint
Think about the difference between passive data and a triggered action.
Public Properties and Public Methods Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
@api isn't only for passive data — it can expose an imperative action a parent triggers on demand, the right tool when a parent needs to tell a child "do this now" rather than just "here's some data."