What is the best way to communicate between two child Lightning components using events?
For example if I have one parent CMP_MAIN and two child components CMP_1 and CMP_2. I want to send parameter from CMP_1 to CMP_2. What is best way to do that?
This is done through an application event, which means that every component involved needs to do something to coordinate their efforts.
The event needs to be defined with whatever properties you want:
<aura:event type="APPLICATION">
<!-- include aura:attribute elements here -->
</aura:event>
The source component needs to register its ability to fire these events:
<aura:component>
<aura:registerEvent name="localName" event="c:appEvent" />
</aura:component>
In the controller, you can fire these events:
fireEvent: function(component, event, helper) {
var event = $A.get("e.c:appEvent");
event.setParams( { } ); // Set your attributes
event.fire();
}
The destination needs to register a handler to handle these events.
<aura:component>
<aura:handler event="c:appEvent" action="{!c.handleAppEvent}" />
The container should also handle the event. This prevents components outside your component hierarchy from getting the event (e.g. you have multiple copies of your components on a page).
<aura:component>
<aura:handler event="c:appEvent" action="{!c.containEvent}" />
<c:CMP_1 />
<c:CMP_2 />
</aura:component>
The containEvent method should stop propagation:
containEvent: function(component, event, helper) {
event.stopPropagation();
}
This can be a major performance boost if there are many copies of your component within an app, Lightning page, etc. If you have no container event, this allows the source to communicate with the destination even if they are not in the same component hierarchy at all.
Since the two components CMP_1,CMP_2 belongs to the same level in the containment hierarchy, you need to use Application event for the inter component communication.
The link over here discusses the same usecase and I believe this will help you out.