0

I have LWC parent and child component. The parent component is a form that has a submit button. Upon submission, I want the parent component to access a specific variable in a specific child component.

Right now the only approaches that I am aware of for passing data are:

  1. Events
  2. Event Bubbling

Is there a way to "Get" a variable on-demand from the parent component?

1 Answer 1

1

The child can expose properties and methods to the parent via the @api decorator.

As a getter property:

export default class Child extends LightningElement {
  #displayState; // private variable
  @api get displayState() {
    return this.#displayState;
  }
}

Which the parent can then read:

const childDisplayState = this.template.querySelector('c-child').displayState;

You can also make this a public method:

export default class Child extends LightningElement {
  #displayState; // private variable
  @api getDisplayState() {
    return this.#displayState;
  }
}

Which you call as a method:

const childDisplayState = this.template.querySelector('c-child').getDisplayState();

Typically, it does make more sense for the child to keep the parent updated, but if you need this on-demand communication, either of these techniques can work.

3
  • Please change your name for sfdcgod Jul 7, 2022 at 1:23
  • First snippet says getter but it is actually a method. Basically, both snippet 1 and 2 are same.
    – javanoob
    Jul 7, 2022 at 18:06
  • 2
    @javanoob a getter is a special type of function that looks like a property. So, while they are both function-like, you cannot call a getter like you would a function. That's why the terminology is written as it is.
    – sfdcfox
    Jul 7, 2022 at 18:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .