Introduction to Lightning Web Components – #LWC

As we all know that Salesforce has introduced the new concept to develop the Lightning Components which is LWC and is beta mode. In this post, we are going to learn how we can start working with LWC and all about LWC

I have recorded the videos regarding the same how we can set up the VS Code to start the coding with Salesforce DX. As, LWC is in beta mode and not available either in Sandbox or Developer environment we need to work with Salesforce Spring 19 Pre-Release Org. Here is the video which will take you to step by step how you can set up the tools and start development.

  • What is LWC?
  • Existing System
  • New LWC Structure
  • Comparison of Aura Framework and LWC
  • Setup Visual Code studio
  • Setup Salesforce CLI
  • Create Hello World LWC
  • Walkthrough with the key concept of LWC

Next Step – What the next video

  • LWC Folder Structure.
  • Supported Salesforce Experiences and Tools
  • Unsupported Experiences and Tools
  • Reactive Properties in JavaScript.
    • Public
    • Private
  • How to use attributes in LWC.
  • How to call the JavaScript method from LWC.

Sharing is Caring 🙂 If you have any doubt or query please comment them below in the comment box or you can reach me @ sfdcpanther@gmail.com OR you can tweet me @cloudyamit

Advertisements

Dynamic Binding Salesforce Lightning Component(Generic)

Welcome back All, here we will learn about the dynamic field of Lightning Component. As Most of you must be aware of that In Lightning, Component Dynamic component is not available. Recently I was working on one of my projects and implemented the Dynamic binding using the lightning component so I am going to share how I implemented the same so that it may help others.

As we all know that we can use the Dynamic Binding in the VisualForce page but in Lightning Component it is not Possible. 

In this example, We will show the list of Objects in a picklist and when user will select any object it will dynamically show the TOP 15 records in a table.

Output 

OutPut.png

Step1 – Create Apex Class

DynamicBindingDemoController.class

Step2 – Create the Lightning Component

DynamicBindingDemo.cmp

See the comments into the component.

Step3: – Click on Controller from the right and paste the below code for Controller Javascript

DynamicBindingDemoController.js


({
doInit : function(component, event, helper) {
helper.onInit(component, event, helper);
},
doHandleChange : function(component, event, helper) {
helper.onHandleChange(component, event, helper);
},
})

Step4: – Click on Helper from the right and paste the below code for Helper Javascript

DynamicBindingDemoHelper.js


({
onInit : function(component, event, helper) {
/* Call the Apex class method to fetch the List of all object */
var action = component.get('c.listAllObject');
action.setCallback(this, function(response){
var state = response.getState();
if(state === 'SUCCESS' && component.isValid()){
/* set the value to the attribute of the component */
var responseValue = response.getReturnValue();
var lstOptions = [];
for(var i=0; i < responseValue.length; i++){
lstOptions.push({
value : responseValue[i].split('####')[1],
key : responseValue[i].split('####')[0]
});
}
lstOptions.sort();
component.set('v.objectList', lstOptions);

}else{
var errors = response.getError();
$A.log(errors);
if(errors || errors[0].message){
console(errors[0].message);
}
}
});
$A.enqueueAction(action);
},
onHandleChange : function(component, event, helper){
/* Call this method whenever user will select the Obejct
* and show the Dynamic Content */
var selObject = component.find('selectObject').get('v.value');
var action = component.get('c.listAllFields');
if(selObject!=null && selObject!='' && selObject!=undefined){
action.setParams({
"objectName" : selObject
});
action.setCallback(this, function(response){
var state = response.getState();
if( state === 'SUCCESS' && component.isValid()){
//component.find("dynamicBody").set("v.body",[]);
component.find('sfdcDiv').set("v.body",[]);
var responseValue = response.getReturnValue();
var objectValue = responseValue.sObjectData;
var fieldList = responseValue.fieldList;

/* Create Dynamic Table */
var sObjectDataTableHeader = [];
// Create table Header
for (var i=0; i < fieldList.length; i++) {
sObjectDataTableHeader.push(fieldList[i].label);
}
console.log(sObjectDataTableHeader);
//Get the count of columns.
var columnCount = sObjectDataTableHeader.length;
//Create a HTML Table element.
var table = document.createElement("TABLE");
//table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = sObjectDataTableHeader[i];
headerCell.className='hearderClass';
row.appendChild(headerCell);
}
var dvTable = document.getElementById("sfdctable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
/* Create Dynamic Table End */

if(objectValue.length){
for(var j=0; j < objectValue.length; j++){
// Dynamic table Row
row = table.insertRow(-1);
// Dynamic Table Row End
for (var i=0; i < fieldList.length; i++) {
// Dynamic table Row
var cell = row.insertCell(-1);
cell.innerHTML = objectValue[j][fieldList[i].apiName];
component.set('v.isSending' , false);

}
}
}else{

}
}else{
var errors = response.getError();
$A.log('Error Details '+errors);
if( errors || errors[0].message){
console.log('Error Details '+errors[0].message);
}
}
});
$A.enqueueAction(action);
}else{
component.set('v.isSending' , false);
}
},
})

See the comments.

Step5: – Create Lightning Application

DynamicBindingDemoApplication.app

<aura:application access=”Global” extends=”force:slds” >
<c:DynamicBindingDemo />
</aura:application>

Click on Preview to see the output of the component.

Happy learning 🙂

Sharing is caring 🙂 😉

Resource:- 

OPFOCOUS Blog

Complete Code

 

 

 

How to Call Salesforce API from Lightning Component

You may have heard about that we can not make the Salesforce API Call directly from the lightning component. If you do make the callout from the lightning component then you will get the below error

INVALID_SESSION_ID:This session is not valid for use with the API.

For Example when you will execute the below code from the Developer Console then you will get the Valid Response


HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
HttpResponse resp = new HttpResponse();

req.setMethod('GET');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v41.0/query?q=Select+Id,+Name+From+Account');
resp = h.send(req);
System.debug('#### Response Status '+resp.getStatus());
System.debug('#### Response Status Code '+resp.getStatusCOde());
System.debug(resp.getBody());

But if you will call the same block from the Lightning Component then you will get INVALID_SESSION_ID:This session is not valid for use with the API. Error.

I gone through with this error and found THIS SALESFORCE DOCUMENT where they have specified why we can not make API Call from JavaScript Code.

After reading the document, I have come up with 2 Solutions that are given below: –

1 – Connected App and Named Credentials as Callout Endpoints and Auth Providers

2 – Using VF Page – VF page will be used to get the Session Id of the current log in user and this VF page will be used into Apex class for fetching the Session Id.

In this tutorial we will use VF page for making callout because it is an easy and simple method method. Follow the below steps

Step1 – Open Developer Console, File -> New -> VisualForce Page -> Enter Name “GetSessionIdVF” -> OK. Use below code for VF Page


<apex:page >
 Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id
</apex:page>

Step2 – Create a New Class which will use this VF page to get the Session Id and making API Call Out. File -> New -> Apex Class -> Name it “ApiCallLightningComponent” -> OK. Use below code for the class.


public class ApiCallLightningComponent {
 /*
 * @Name : - fetchUserSessionId
 * @Description: - Call the VF page and get the Log In Use Session Id
 * @Params : - none
 * @ReturnType : - String
 */
 public static String fetchUserSessionId(){
 String sessionId = '';
 // Refer to the Page
 PageReference reportPage = Page.GetSessionIdVF;
 // Get the content of the VF page
 String vfContent = reportPage.getContent().toString();
 System.debug('vfContent '+vfContent);
 // Find the position of Start_Of_Session_Id and End_Of_Session_Id
 Integer startP = vfContent.indexOf('Start_Of_Session_Id') + 'Start_Of_Session_Id'.length(),
 endP = vfContent.indexOf('End_Of_Session_Id');
 // Get the Session Id
 sessionId = vfContent.substring(startP, endP);
 System.debug('sessionId '+sessionId);
 // Return Session Id
 return sessionId;
 }
 /*
 * @Name - makeAPICall
 * @Description - Responsible for making API Call out
 * @params - None
 * @ReturnType - String
 */
 @AuraEnabled
 public static String makeAPICall(){
 String sessionId = fetchUserSessionId();
 HTTP h = new HTTP();
 HTTPRequest req = new HTTPRequest();
 HttpResponse resp = new HttpResponse();
 req.setMethod('GET');
 req.setHeader('Authorization', 'Bearer ' + sessionId);
 req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v41.0/query?q=Select+Id,+Name+From+Account');
 resp = h.send(req);
 System.debug('#### Response Status '+resp.getStatus());
 System.debug('#### Response Status Code '+resp.getStatusCOde());
 System.debug(resp.getBody());
 return JSON.serialize(resp.getBody());
 }
}

See the comments.

ApiCallLightningComponent class contains 2 methods fetchUserSessionId and makeAPICall, One for getting the Session Id and Other for making the Callout that will be called from the JavaScript.

Step3 – Create a lightning component, File -> New -> Lightning Component -> Name it “MakiAPICall” -> OK. Use below code for the Component


<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes, flexipage:availableForRecordHome,force:hasRecordId, forceCommunity:availableForAllPageTypes, force:lightningQuickAction" controller="ApiCallLightningComponent" access="global" >
<div class="slds-m-around_x-small">
			<lightning:button variant="brand" label="Make CallOut" iconName="action:apex" iconPosition="left" onclick="{!c.doHandleClick }" /></div>
</aura:component>

Click on the Controller and use below code


({
doHandleClick : function(component, event, helper) {
helper.onHandleClick(component, event, helper);
}
})

Click on the helper and then use below code for helper


({
onHandleClick : function(component, event, helper) {
// Get the action of Controller (Apex) Class
var action = component.get('c.makeAPICall');

// set the callback which will return the response from apex
action.setCallback(this, function(response){
// get the state
var state = response.getState();
if( (state === 'SUCCESS' || state ==='DRAFT') && component.isValid()){
// get the response
var responseValue = response.getReturnValue();
// Parse the respose
var responseData = JSON.parse(responseValue);
alert(responseData);
//alert(responseData.totalSize);
console.log(responseData);
} else if( state === 'INCOMPLETE'){
console.log("User is offline, device doesn't support drafts.");
} else if( state === 'ERROR'){
console.log('Problem saving record, error: ' +
JSON.stringify(response.getError()));
} else{
console.log('Unknown problem, state: ' + state +
', error: ' + JSON.stringify(response.getError()));
}
});
// send the action to the server which will call the apex and will return the response
$A.enqueueAction(action);
}
})

Step4 – In Final Step Test the Component using Lightning Application. File -> New -> Lightning Application -> Enter Name -> Submit -> Use below Code


<aura:application extends='force:slds' >
<c:MakiAPICall/>
</aura:application>

Note: – If Your component name is different then use the name of your component instead of MakiAPICall.

Output of the above code

Call API From Lightning Component

You can find the complete Here.

Happy Learning 🙂

Happy Coding 😉

Sharing is Caring

Resources –

 

Salesforce Lightning Interview QA

I have compiled some Interview Questions related to Salesforce Lightning that are given below:

1 – One User is viewing a Lightning Component in which some fields are being displayed and in the mean time some other user have changed the value of the field. How do you ensure that user will see the updated value?

Answer – Using platform event. Streaming API will not work into the Lightning Environment.

2 – What is Lightning Data Service(LDS) ? What are the benefits of using LDS?

Answer – LDS is a standard controller for Lightning Component. Using Lightning Data Service we can Create, Retrieve, Delete and update records for which we do not need to write the apex class. Lightning Data Services ensures the FLS by itself. For more info see Here.

3 – When we can not use LDS in Lightning Component?

Answer – LDS is used for single record so when we are dealing with Bulk records then we can not use LDS.

4 – What is main difference between Lightning Component and Visual Force Pages OR Why we should go for Lightning Component?

Answer – Visualforce components are page-centric and most of the work is done on the server. Lightning is designed from the component up, rather than having the concept of a page as its fundamental unit. Lightning Components are client-side centric, which makes them more dynamic and mobile friendly.

5 – Will Lightning Components be replacing Visualforce?

Answer – No.

6 – Is Lightning an MVC framework ?

Answer – No, it’s component based framework.

7 – What aura:method does in Lightning Component?

Answer – We can Use aura:method to define a method as part of a component’s API. This enables us to directly call a method in a component’s client-side controller instead of firing and handling a component event

8 – How many Components can be used in a single lightning application?

Answer – There is no Limit.

9 – Will Visual Force page will stop working on Lightning UI?

Answer – No, VF page will work in the Lightning UI as Classic UI.

10 – Can we include external Library into Lightning Component?

Answer – Yes, we can include multiple library into Lightning component.

More QA updates soon 🙂

Call Child Component Controller From Parent Component – Aura Method

In my previous posts we have seen how we can use application and component events and when we should go for. You all must be thinking what if we want to call the controller of child component controller from the parent component. So, in this post we will see how we can do the above things.

aura:method: – Use <aura:method> to define a method as part of a component’s API. This enables you to directly call a method in a component’s client-side controller instead of firing and handling a component event.

The <aura:method> tag has these system pre defined attributes that we can use

Name: – The method name. Use the method name to call the method in JavaScript code.

Action: – The client-side controller action to execute

Access: – he access control for the method. Valid values are: public and global

Description: – The description of method.

Declaring Parameters: – We can also use parameters to send the values from parent to child using the attributes.

Below is sample of child Component

““

<aura:method name=”sampleMethod” action=”{!c.doAction}”
                        description=”Sample method with parameters”>
       <aura:attribute name=”param1″ type=”String” default=”parameter 1″/>
       <aura:attribute name=”param2″ type=”String” />
</aura:method>

““

Define the action that needs to be executed when “sampleMethod” gets called from the parent component. Create a method into Controller of Child Component. Child Component Controller sample code.

““

({
doAction : function(cmp, event) {
var params = event.getParam(‘arguments’);
if (params) {
var param1 = params.param1;
// add your code here
}
}
})

““

Get the value into the child controller: – Retrieve the arguments using event.getParam(‘arguments’). It returns an object if there are arguments or an empty array if there are no arguments. For example if you are passing 2 parameters then you can get like below

Step1: – Get the array of all the arguments

var params = event.getParam(‘arguments’);

Step2: – Now, get the value of the attribute using the name of the attribute.

var param1 = params.param1;

var param2 = params.param2;

In Final Step Call the method from the Parent Code: –

Step1: – Call the child component inside the parent component using the syntax like below and use aura:id for the child component which will let you find the child component and then you can call the controller method.

<c:childComponent aura:id=’childCmp’ /> – Use this Syntax if no namespace is defined by you.

<yourNameSpace:childComponent aura:id=’childCmp’ /> Use this Syntax if you have your own       namespace is defined by you.

Step2: – Create a button OR any event in which you want to execute the child controller method.

<lightning:button variant=”brand” label=”Submit” onclick=”{! c.handleClick }” />

Step3 : – Call the child controller method from the parent controller method.

({

handleClick : function(component, event, helper){

// Find the child component using the aura:id that we have given while creating the parent component and store the same into a variable.

var childCmp = component.find(‘childCmp’);

// Call the Child Controller method using childCmp variable dot method name defined into the child component

childCmp.sampleMethod(‘Sample Value for Param 1’, ‘Sample Value For Param 2’); // Pass the parameters here

}

})

Example: – For an example we will take a very simple scenario for creating quick contact for the selected account doing this we will reduce the work of going to account detail page and then create a contact from there. You can get the complete code from Here.

Component will look like below.

Aura Method.gif

 

Happy Coding 🙂

If you have any questions let me know in comments Section.

Resource: –

Salesforce Document

Top 10 Features for Lightning Development – Spring 18 Release

New Lightning Components

Note: – The following components are new and require API version 42.0 and later.

  • lightning:carousel (Beta): – A collection of images that are displayed horizontally one at a time. As this is a beta version feature it will have some limitations.

base_carousel

  • lightning:formattedAddress: – Displays a formatted address that provides a link to the given location on Google Maps.

base_formattedAddress

  • lightning:inputAddress: – Input fields represents an address compound field with support for street, city, province, postal code, and country.

base_inputAddress.png

  • lightning:inputField : – An editable field with a label, help text, and value that corresponds to a field on a Salesforce object. This component must be nested in a lightning:recordEditForm component.
  • lightning:inputName: – Represents a name compound field with support for salutation, first name, middle name, last name, informal name, and suffix.

base_inputName.png

  • lightning:listView : – Represents a list view of records that you own or have read or write access to, and records shared with you.

base_listView.png

  • lightning:recordEditForm : – A record edit or record create layout that displays one or more fields provided by lightning:inputField.

base_inputField.png

  • lightningsnapin:prechatAPI : – Enables customization of the user interface for the pre-chat page in Snap-ins Chat.

Changed Lightning Components

lightning:datatable: – Datatable an amazing feature that we got in the previous release (winter 18) has many new features in the coming release Spring 18.

Text wrapping and clipping within a column is now supported. Text wrapping expands the height of the rows to reveal more content. Content is clipped by default if the number of characters is more than what the column width can hold. To toggle between the two views, select Wrap text or Clip text from the dropdown menu on the column header.Other features that are now supported include:

  • Appending icons to the header column
  • Header-level actions
  • Infinite loading of rows
  • Row-level actions
  • Selecting rows programmatically
  • Using a button as a data type

These features are captured by the following lists of attributes, column properties, and data types.

The following attributes are new.

  • enableInfiniteLoading—Enables or disables infinite loading. The default is false.
  • isLoading—Specifies whether more data is being loaded, and displays a spinner if there is. The default is false.
  • loadMoreOffset—Determines when to trigger infinite loading based on how many pixels the table’s scroll position is from the bottom of the table. The default is 20.
  • selectedRows—Enables programmatic row selection with a list of keyField values.
  • maxRowSelection—Maximum number of rows that can be selected. Checkboxes are used for selection by default, and radio buttons are used when maxRowSelection is 1.
  • onheaderaction—The action triggered when a header action is clicked. By default, it also closes the header actions menu.
  • onloadmore—The action triggered when infinite loading loads more data.
  • onresize—The action triggered when the table renders columns each time it resizes a column.
  • onrowaction—The action triggered when a row action is clicked. By default, it also closes the row actions menu.
  • rowNumberOffset—Determines where to start counting the row number. The default is 0.
  • showRowNumberColumn—Shows or hides the row number column. Set to true to show the row number column. The default is false.

The following column properties are new.

  • actions—Appends a dropdown menu of actions to a column.
  • cellAttributes—Provides additional customization, such as appending an icon to the output. You can pass in these attributes: iconName, iconLabel, iconPosition.
  • iconName—The Lightning Design System name of the icon. Names are written in the format standard:opportunity. The icon is appended to the left of the header label.

The following data types are now supported.

  • action—Displays a dropdown menu using lightning:buttonMenu with actions as menu items. This data type supports these typeAttributes properties: rowActions and menuAlignment.
  • button—Displays a button using lightning:button. This data type supports these typeAttributes properties: disabled, iconName, iconPosition, label, name, title, variant.

The url data type now supports the following typeAttributes property.

  • label—The text to display in the link. Give label of the record name or anything you want.

The date type now supports the following typeAttributes properties.

  • day—Valid values are numeric and 2-digit.
  • era—Valid values are narrow, short, and long.
  • hour—Valid values are numeric and 2-digit.
  • hour12—Determines whether the time is displayed as 12-hour. If false, time displays as 24-hour. The default setting is determined by the user’s locale.
  • minute—Valid values are numeric and 2-digit.
  • month—Valid values are 2-digit, narrow, short, and long.
  • second—Valid values are numeric and 2-digit.
  • timeZone—The time zone to use. Implementations can include any time zone listed in the IANA time zone database. The default is the runtime’s default time zone. Use this attribute only if you want to override the default time zone.
  • timeZoneName—Valid values are short and long. For example, the Pacific time zone displays as PST if you use short or Pacific Standard Time if you use long.
  • weekday—Valid values are narrow, short, and long.
  • year—Valid values are numeric and 2-digit.

 

Happy Reading 🙂

You can try all these features into the Sandbox Org once this release has been loaded into Sandbox after 5th Jan OR 6th of Jan 2018.

Resources: –

Salesforce Release Document

 

Play with Events in Lightning Component – Part 3

Application Event: – Whenever our component are not connected to each other and in that case we wanted to communicate between the components then we go for application event. We do not need to register the application event, handler is need to handle the application event.

Use Case: – When we want to communicate with the components that are not related to each other but need to reflect the data when there is any change in the other component. For example: – We have 2 components, 1st shows the List of All Contacts record and when we click on any contact we want to show the details of the contact then we will use Application Event.

In order to use Application event we need to follow the Four simple steps

  1. Create Application Event
  2. Fire the event from the child component
  3. handle the event into Parent Component
  4. Execute the action into Parent Component

Step 1 – Create Application Event

Open developer console and then File -> New -> Lightning Event -> name it applicationEvent and use below code.

<aura:event type=”APPLICATION” description=”Event template” >
<aura:attribute name=”testWord” type=”String” />
</aura:event>

Step 2 – Register the event

Unlike the Component we do not need to register the Application Event.

Step 3 – Fire the component Event

Use below code in javascript to execute the event.

({
handleClick : function(component, event, helper) {
    var appEvent = $A.get(‘e.c:applicationEvent’);
    appEvent.setParams({
            “testWord” : ‘Value From Application Event’
     });
     appEvent.fire();
   },
})

 

Explanation : –

  1. $A.get(‘e.c:applicationEvent’); – Finds the event with the name provided after c: and in our case it it applicationEvent.
  2. setParams : – is used to send the parameters to the parent component if we are using any attribute in the event. In our case we have used attribute testWord
  3. fire() :- Executes the event

Step 4: – Handle the Event in any Component

A single line of code to handle the event into the parent component

<aura:handler event=”c:applicationEvent” action=”{!c.doHandleCompEvent}” />

Explanation : –

  1. event: – Same as the type that we have provided at the time of registering the event
  2. action: – calls the java script controller method and there you can do rest of your stuffs

Step 5: – Do Action in JS controller

doHandleCompEvent : function(component, event, helper){

      var eventParam = event.getParam(‘testWord’);

     // getParams is used to get the parameters that we have passed from the child component

},

Note: – Both Application Event Handler and Application Event notifier component must be part of the same component. For example let call that component as aeContainer.cmp which will contain both the components.

<aura:component >
        <c:applicationEventComp1 />
        <c:HandlerComponent/>
</aura:component>

Happy Coding 🙂 😀

Resource :-

Complete Code

Salesforce Document

Play with Events in Lightning Component – Part 2

Hi All, in this tutorial we will see how Component Events works and when we should go for Components events instead of Application Events.

Component Events: – The main question is that what is the events(component) and when we should go for it, Component event is the custom event that we define for our use which is raised by the component and We should go for this event when we want to send data/want to refresh the parent component from the child component(whenever particular criteria met or particular action executed from the child component).

In order to use component events we need to follow the Four simple steps

  1. Create Component Event
  2. Register the event on the child component
  3. Fire the event from the child component
  4. handle the event into Parent Component

Use Case: – The most used and basic use case of component event is when we are creating custom lookup in Salesforce lightning component then we go for component event because we need to send the search param to parent component which will take search param and then display the result.

Step 1 – Create Component Event

Open developer console and then File -> New -> Lightning Event -> name it compEvent and use below code.

<aura:event type=”COMPONENT” description=”Event template” >
                            <aura:attribute name=’testWord’ type=’String’ />
</aura:event>

Step 2 – Register the event

To register an event we only need to put a single line of code in our child component(The component from where you want to execute the event).

<aura:registerEvent name=’testEvent’ type=’c:compEvent’ />

In the above code

name – you can give what ever you want and this name will be used in javascript controller to get the event.

type – type must be in namespace:EventName format if you do not have any namespace the c is the default namespace that we use.

Step 3 – Fire the component Event

Use below code in javascript to execute the event.

var compEvent = component.getEvent(‘testEvent’);

compEvent.setParams({

      “testWord” : “Hello Event”

});

compEven.fire();

Explanation : –

  1. getEvent(‘testEvent’); – getEvent is a method in component and inside the method we pass the event name in our case name is testEvent
  2. setParams : – is used to send the parameters to the parent component if we are using any attribute in the event. In our case we have used attribute testWord
  3. fire() :- Executes the event

Step 4: – Handle the Event in Parent Component

A single line of code to handle the event into the parent component

<aura:handler name=’testEventevent=’c:compEvent’ action='{!c.doHandleCompEvent}’ />

Explanation : –

  1. Name: – name must be same as you have provided while registering the event which will tell the component that which event needs to be handle
  2. event: – Same as the type that we have provided at the time of registering the event
  3. action: – calls the java script controller method and there you can do rest of your stuffs

Step 5: – Do Action in JS controller

doHandleCompEvent : function(component, event, helper){

      var eventParam = event.getParam(‘testWord’);

     // getParams is used to get the parameters that we have passed from the child component

},

Resource: –

Salesforce Developer Document

Play with Events in Lightning Component – Part 1

Events plays very important role while developing the Lightning component and communicating between the components.

Introduction :-

The Lightning framework uses event-driven programming. You write handlers that respond to interface events as they occur. The events may or may not have been triggered by user interaction.

In the Lightning Component framework, events are fired from JavaScript controller/helper actions. Events can contain attributes that can be set before the event is fired and read when the event is handled.

There are two types: component or application.

1- Component Events
A component event is fired from an instance of a component. A component event can be handled by the component that fired the event or by a component in the containment(Upper level) hierarchy that receives the event.
2 – Application Events
Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified.

Main difference between application and component event is that Component event can only be handled by parent component and application event can be handled in all over the application.

Component Event needs to be register and handled wherever application event only need to handle and do not need to register.

In next post we will see how Component Event works and when to use component events while developing the custom lightning component.