Is it possible to fire an event from a lightning web component and handle in another lightning web component which is not in containment hierarchy? This is achievable in Aura component using application event.
[SalesForce] Is it possible to fire an event from a LWC and handle in another LWC which is not in containment hierarchy
Related Solutions
Its a special case where in the parent won't listen to child's event, for doing so you would need to pass the reference of parent controller's method while creating it.
So add attributes here:
$A.createComponent("c:TestChild", {},
like:
$A.createComponent("c:Child_213329", {
"fromModal": component.getReference("c.fromModal")
},
With parent event would be binded and called whenever parent fires that specific event.
Note: I might be missing something; looks like some kind of bug in lightning:overlayLibrary
It just doesn't works the first time popup is opened but works afterwards.
Passing parameter to parent:
Add params to the component event, TestChildController.js-
({
callParent: function (component, event, helper) {
var evt = component.getEvent('fromModal')
.setParams({
"message" : "A component event fired me. " +
"It all happened so fast. Now, I'm here!" })
.fire();
}
});
Get parameter in TestParentController.js-
fromModal: function (component, event, helper) {
var message = event.getParam("message");
console.log('message from modal', message);
}
Complete code
used for testing/demo.
To simplify things, lets call your LWC, component A, and your Aura component, component B.
Currently your components are independent, thus in tree terms, your component B (Aura) is not an ancestor of the component A (LWC).
There are two quick ways you could fire an event from component A (LWC) to component B (Aura)
1) Create a new Aura component that encapsulates component A (LWC). Component A then would fire a standard DOM event and the new Aura component would listen for the event and then re-fire the event as an application Aura event. Component B would then listen for the event and handle it. Something like this gist.
2) Create a child LWC component, call it componentC, in component B (Aura). Fire the event via pub-sub in component A (LWC). Then in componentC, listen and handle your event then re-fire it as a standard DOM event that would be handled by your Aura component, component B.
More resources:
Best Answer
Yes. It can be achieved using the pub-sub model.
Refer to Communicate Between Components documentation for more details.
You can find the
pubsub
module here on lwc-recipe