Saturday, May 18, 2019

Component event in lightning

Component Events are fired by the child components and handled by the parent component.
A lightning framework is an event driven architecture  i.e communication between the components takes place by using events.

In the below example we will study how to fire events from the child component and handle them in the parent component.

Component Event: (Name=CompEvent)

<aura:event type="COMPONENT" description="Event template" >
    <aura:attribute name="storeMessage" type="String"/>
</aura:event>

Child Component: (Name=ChildComp) 

<aura:component >
    <aura:registerEvent name="regInChild" type="c:CompEvent"/>
    <aura:attribute name="textMessage" type="String" default="Part from child comp"/>
    <lightning:button label="Click To Fire" onclick="{!c.doHandleEvent}"/>
</aura:component>

Javascript controller:

({
 doHandleEvent : function(component, event, helper) {
  var cmpEvnt=component.getEvent("regInChild");
        cmpEvnt.setParams({
            storeMessage : component.get("v.textMessage")     
        });
        cmpEvnt.fire();
 }
})


Parent Component: (Name=ParentComp)

<aura:component >
    <aura:handler name="regInChild" event="c:CompEvent" action="{!c.doHandleFromChild}"/>
    <aura:attribute name="parentMessage" type="String" />
    <c:ChildComp/>
    {!v.parentMessage}
</aura:component>

Javascript controller:


({
 doHandleFromChild : function(component, event, helper) {
        var valueFromEvent=event.getParam("storeMessage");
        component.set("v.parentMessage",valueFromEvent);
 }
})

Component event in lightning

No comments:

Post a Comment