Hello friends, In this post we are going to learn about lightning component event. We used component event in lightning component to communicate between components. so let's understand this using example.
Component event in lightning component
In Salesforce, lightning is based on event-driven architecture which used to communicate between different events. Component events are fired by the child components and handle by the parent component, we required parent child relationship between components to use the component event.
Implementation:
For component event implementation, we have to create two components. i.e. a) Child b) Parent and also a lightning event.
To create lightning event, Navigate to Developer Console | File | New | Lightning Event and create a lightning event named "SampleCmpEvent" and replace the following markup.
SampleCmpEvent.evt
<aura:event type="Component" description="Component Event">Child.cmp
<aura:attribute type="string" name="empName"/>
</aura:event>
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >ChildController.js
<aura:registerEvent name="cmpEvent" type="c:SampleCmpEvent"/>
<div class="slds-m-around_xx-large">
<lightning:button label="Click to fire the event" variant="brand" onclick="{!c.FireEvent}"/>
</div>
</aura:component>
({Parent.cmp
FireEvent : function(component, event, helper) {
var cmpevt=component.getEvent("cmpEvent");
cmpevt.setParams({
"empName" : "My Employee"
});
cmpevt.fire();
}
})
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >ParentController.js
<aura:handler name="cmpEvent" event="c:SampleCmpEvent" action="{!c.ComponentEventHandler}"/>
<aura:attribute name="message" type="String"/>
<div class="slds-m-around_xx-large">
<p>{!v.message}</p>
</div>
<!--Include child component inside Parent component-->
<c:Child/>
</aura:component>
({
ComponentEventHandler : function(component, event, helper) {
var message = event.getParam("empName");
component.set("v.message", "Hi! "+message);
}
})
Preview: To see the output you have to include Parent components in lightning application.
Preview.app
<aura:application extends="force:slds">
<c:Parent/>
</aura:application>
Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.
0 Comments
Post a Comment