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:
...
And the parent should handle it:
...
Alternatively, you can set an @api get and set method, then return some sort of backing variable that may have been updated:
Which you then query on-demand:
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).