Lightning Web Components – Passing Data to Sibling Components on Change Events

I have below lwc components hierarchy.Custom events are fired in the Child2 , handle it in Parent , do some modification to the payload and assign it to a @track property (filters)
in parent . On click of a button in Child1.cmp , it should always save the values of childfilters. However, childfilters is undefined , though filters is not a undefined.
How can I have childfilters in Child1.js same value as filters in Parent.js during button click in Child1.js

Parent.html:

<Parent>
    <Child1> childfilters = {filters}
    </Child1>

    <Child2>
    </Child2>
</Parent>

Parent.js:

@track 
 filters = [];
 // Some code
 filters = SomeValues;

Child1.html

<Child 1>
    <lightning:button onclick = {savefilter}>
    </lightning:button>
 </Child 1>

Child1.js:

@api
 childfilters;
 savefilter(){
     console.log('childfilters '+childfilters); // this logs undefined 
 }

Best Answer

Your child should notify the parent when there's a change:

<lightning-input ... onchange={handleFilterChange}>
</lightning-input>

...

// Inside child1.js
handleFilterChange(event) {
  this.dispatchEvent(new CustomEvent('filterchange', {
    detail: { childfilter: { /* fill this part out */ } } }
  );
}

And the parent should handle it:

<c-child1 childfilters={filters} onfilterchange={handleFilterChangeEvent}>
</c-child1>

...

handleFilterChangeEvent(event) {
  this.filters = event.detail.childfilter;
}

Alternatively, you can set an @api get and set method, then return some sort of backing variable that may have been updated:

_filters;
@api get filters() {
  return this._filters;
}
set filters(value) {
  this._filters = value;
}

Which you then query on-demand:

const filters = this.template.querySelector('c-child1').filters;
// do something here

I wrote a complete working example using generic HTML in this web component.

The demo doesn't build a complete complex object, but you can build as complicated of a detail property as you need.

If you use the get/set method, it is recommended that you validate the input instead of just accepting whatever comes in (as in my example).