Friday 21 September 2018

Dynamically Creating Components Part 1:- createComponents

You Can create the Dynamic Component in Clint Side with javaScript using "$A.createComponent()".  If you want to create multiple component together then use "$A.createComponents()".

"$A.createComponent()" accept the three parameters. Please check this post for more detail.
1) Type
2) Attribute
3) CallBack (cmp, status, errorMessage)

Syntax :-

$A.createComponent( String type, Object attributes, function callback )

Use Case:- Create a new button onclick on existing button. And Destroying Dynamically Created Components.
Solution:- We can do the same with the help of "$A.createComponent()".

Sample Code.


<aura:component >
    <aura:attribute name="IsBottonVisible" type="boolean" default="false"/>
    <lightning:button variant="brand" label="Create New Button"
                      title="Create New Button" onclick="{! c.CreateNewButton }" />
        <p>Dynamically created button</p>     <BR/><BR/>



NOTE:- I created IsBottonVisible Attribute to avoid creating multiple Button.


    CreateNewButton : function(component, event, helper) {
        var isButtonVisible = component.get("v.IsBottonVisible");
        if(isButtonVisible == false){
                    "aura:id": "UniqueAuraId",
                    "label": "Destroy Me",
                    "onclick": component.getReference("c.DestroyMe")
                function(newButton, status, errorMessage){
                    if (status === "SUCCESS") {
                        var body = component.get("v.body");
                        component.set("v.body", body);
                        isButtonVisible= true;
                        component.set("v.IsBottonVisible", isButtonVisible);
                    else if (status === "ERROR") {
                        console.log("Error: " + errorMessage);

    DestroyMe : function(cmp) {
        // Find the button by the aura:id value
        console.log("button: " + cmp.find("UniqueAuraId"));
        var comp = cmp.find("UniqueAuraId")
        cmp.set("v.IsBottonVisible", false);


<aura:application extends="force:slds">


 Please check our old post on Lightning :-
1) Invoke Apex from Lightning Component 

2) Design Resource In Lightning Component Bundle
3) Component Event in Lightning Component | aura:event
4) Modal/Popup in Lightning Component

Feel free to post your feedback or question.

Amit Chaudhary

Capture.JPG  @amit_sfdc    #SalesforceApexHours    @ApexHours
  Salesforce Apex Hours 

1 comment:

  1. Thanks for sharing!