What is the parent-to-child communication pattern using @api methods?
Suggested answer
Parent components can call methods on child components using template refs. Child declares a public method: @api focusInput() { this.template.querySelector('input').focus(); }. Parent HTML: <c-my-input lwc:ref="inputCmp"></c-my-input>. Parent JS: this.refs.inputCmp.focusInput(); (using lwc:ref — available in newer API versions). Older pattern using querySelector: this.template.querySelector('c-my-input').focusInput();. Important rules:
1. @api methods cannot be called in the constructor (child not yet created).
2. Call in connectedCallback, renderedCallback, or event handlers.
3. Only call synchronously — do not await @api method calls.
4. Do not expose @api methods that allow parents to directly mutate child state — prefer event-driven patterns.
Practice content for interview preparation; not an official vendor answer. Verify details against current product documentation.
Community comments (0)
No comments yet.
Sign in or create a free account to add a comment. Comments are moderated before they appear.