To pass values from child aura component to parent, i.e up the hierarchy we need to create a custom lightning event.
FLOW OF A LIGHTNING EVENT
Create > Register > Fire > Handle
We create a component event and is registered in the child components and thereby handled by the parent component.
A component event is fired by a lightning component and can be handled by the component itself or by any other component that is already present in the hierarchy and has the handler for that particular event.
Create the lightning event
Go to developer console and go to File>New>Lightning event. We using aura:event tag and specify the type=’Component’ to create the event. We can create attributes which can be the data to be passed when we fire the event.
compEvent.evt
<aura:event type="COMPONENT" description="Component Event Example">
<aura:attribute name="message" type="String" />
</aura:event>
Register the event in the Notifier or Child component (Sender)
We use aura:registerEvent tag to register the event in the child component. The type is the exact name of the component event and the name in the tag can be whatever we want to name it for the boundaries of the child component.
ChildComponent.cmp
<aura:component>
<aura:registerEvent name="compEvent" type="c:compEvent.evt"/>
<p><lightning:button label="Fire the event" onclick="{!c.fireComponentEvent}" /> </p>
</aura:component>
Fire the event from the JS of the Child component
ChildComponent.js
({
fireComponentEvent : function(component, event) {
var compEvent = cmp.getEvent("compEvent");
compEvent.setParams({
"message" : "Hello " +
"World!" });
compEvent.fire();
}
})
Handle the event in the Parent component (Reciever)
The Parent component contains the above child component. We use the aura:handler tag to handle the event.
ParentComponent.cmp
<aura:component>
<aura:attribute name="messageTemp" type="String" />
<aura:handler name="compEvent" event="c:compEvent" action="{!c.handleCmpEvent}" />
<c:ChildComponent />
<p>{!v.messageTemp}</p>
</aura:component>
ParentComponent.js
({
handleCmpEvent: function(component, event) {
var message = event.getParam("message");
cmp.set("v.messageTemp", message);
}
})
After handling the event, we can get the passed parameters and we can use the data passed by the child component.
Read More: How to pass data or call a method from parent to child aura component
5 thoughts on “How to pass values from Child-to-Parent Lightning Aura component using Component Event”