Monday, August 20, 2018

Creating Lightning Components Dynamically

Through this blog, I will share the approach to create lightning components dynamically by sharing an example in which we will display account summary information by creating summary component dynamically.

I have already posted one blog through which we can create ui:button dynamically and can destroy it. Please refer below URL if you want to refer that before continuing with this blog:

creating or destroying buttons dynamically

Below is snapshot of app which will display recent accounts on left side and on right side, it will display opportunities and case summary for account. You can click on "show Info" link before any account record and its related information will appear on right side dynamically.


Code to create dynamic component

You can use $A.createComponent method which accepts 3 parameters:
  1. ComponentName (String) :Type of component to create like "c:newCmp" etc.
  2. attributes : JSON specify component attributes values
  3. callback function: Once the component is created, this callback function will be invoked.This function can be used to append newly created component to target component. You can place the newly created component inside some div to display.
Below is sample code along with comments to explain steps:

 //find the div markup where you want to display dynamic component
//here "dynamicCmpSection" is aura:id of div
var targetCmp = component.find("dynamicCmpSection");
//create JSON specify all attributes needed for new component
var cmpAttributes = {
                "attribute1": "attribute Value",
"attribute1": "attribute Value"
            }
$A.createComponent(
"c:Demo_DynamicViewCmp", 
cmpAttributes,
function(tempbody) {
//Check if component is valid
if (component.isValid()) {
var targetCmp = component.find("dynamicCmpSection");
//first remove all content inside the div by making its body as null
targetCmp.set("v.body",[]);
var body = targetCmp.get("v.body");
//add newly created component in div
body.push(tempbody);
targetCmp.set("v.body", body);
console.log('***component loaded successfully');
}
}
);

Below is complete code related to snapshot shown in blog.

Hope this Helps!!

No comments:

Post a Comment