Sample Component Event:
Create a sample component type event. Use type=”COMPONENT” in theaura:eventtag for an component event. The attribute type is the one that will differentiate Component event from Application event.
<!--SampleComponentEvent.evt-->
<aura:event type="COMPONENT" description="Sample Component Event">
<aura:attribute name="message" type="String" default="Hello World!!" />
</aura:event>
Child Component:
The event is registered in this component by usingaura:registerEventin its markup.
<!--Child.cmp-->
<aura:component >
<aura:registerEvent name="sampleCmpEvent" type="c:SampleComponentEvent" />
<lightning:button label="Click to fire the event" variant="brand" onclick="{!c.childComponentEvent}"/>
</aura:component>
Child Component JS Controller:
To set the attribute values of event, callevent.setParam()orevent.setParams()
({
childComponentEvent : function(cmp, event,helper) {
//Get the event using registerEvent name.
var cmpEvent = cmp.getEvent("sampleCmpEvent");
//Set event attribute value
cmpEvent.setParams({"message" : "Welcome "});
cmpEvent.fire();
}
})
Parent Component:
The component event handled by the Parent Component that fired usingaura:handlerin the markup. The name attribute in aura:handler must match the name attribute in the aura:registerEvent tag in the Child Component that fires the event.The action attribute of aura:handler sets the client-side controller action to handle the event.
<!--Parent.cmp-->
<aura:component >
<aura:attribute name="eventMessage" type="String"/>
<aura:handler name="sampleCmpEvent" event="c:SampleComponentEvent" action="{!c.parentComponentEvent}"/>
<div class="slds-m-around_xx-large">
<c:Child />
<p>{!v.eventMessage}</p>
</div>
</aura:component>
Parent Component JS Controller:
({
parentComponentEvent : function(cmp, event) {
//Get the event message attribute
var message = event.getParam("message");
//Set the handler attributes based on event data
cmp.set("v.eventMessage", message + 'nikforce.blogspot.com');
}
})