0

I'm using a Parent component TabParentLWC. It has two tabs each of which has tab1childlwc and tab2childlwc as child components . Tab1 is the default visible tab. User makes selections on component inside Tab1. These selections are published by tab1childlwc to UserSelectionMessageChannel. tab2childlwc is subscribing to UserSelectionMessageChannel and it's purpose is to just display the selections. If I were to include tab2childlwc component in the same Tab which is visible when page opens everything works fine. When it is on Tab2, connectedCallback on it will not be called until it is visible and hence it misses out the selections user made on Tab1 before Tab2 is made visible first time, as it hasn't yet started subscribing to the channel. My question is : how do I invoke or ensure that the connectedCallback function of tab2childlwcworks ( and subscription to channel is on) even when the tab on which it is included is not visible?

<template>
<lightning-tabset>
    <lightning-tab label="Tab1">
        <c-tab1childlwc></c-tab1childlwc>
    </lightning-tab>
    <lightning-tab label="Tab2" >
        <c-tab2childlwc></c-tab2childlwc>
    </lightning-tab>
</lightning-tabset>
</template>
1
  • You need to refactor the components to collaborate more. My suggestion: when the tab2childlwc is instantiated it should probably fire a message that is received by the tab1childlwc which ensures it then sends the user selection messages again.
    – Phil W
    Dec 3, 2020 at 15:57

1 Answer 1

2

Maybe this will work for your use case.

From Child1(Tab1) Component Send Custom Event and Subscribe to this event in your Parent Component and store these selected values in an attribute.

Pass this attribute to Child2(Tab2) Component using @api property. So whenever Child2(Tab2) is created will have all the latest selected values.

In case, if you want to handle logic on selected values changes in the child2 component you can also achieve it. Sample code below:

_selectedValues;

@api
get selectedValues() {
  return this._selectedValues;
}
set selectedValues(value) {
  this._selectedValues = value;
  // Handle Changes - Ex: Calling Apex
}
1
  • 1
    Awesome. It works. The approach I took with page composition hit a snag and I was trying to solve the wrong challenge it posed. In my approach a sibling is trying to hand over something to an unborn sibling. Right approach as you suggested should have been, sibling hands it over to the parent and parent HOLDS it and hands over to the sibling/child when it is born - that way whatever happened before the birth of other children are not lost. This is necessitated because of the Tab approach, as I understand the components inside the Tabs get life only when it is made visible . Thank you so much.
    – vino
    Dec 4, 2020 at 18:45

You must log in to answer this question.

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