SalesforceBlue

Feel the rhythm of Salesforce

Aura

Creating Dynamic Aura Component Simplified

Suppose that you have to travel on a business trip to a different city.

You are already overflowing with luggage and not willing to carry an additional lunch bag with you. Rather you plan on buying it at lunchtime from any outlet during the journey.

Thus, you have arranged food items at your own will and at a specified time instead of carrying them with you from the start of the journey.

This analogy is similar to Creating Dynamic Aura Components.

Instead of initializing and loading the component immediately as soon as the page loads, you plan on creating it dynamically at run time based upon certain actions.

Thus, preventing the creation of multiple components during the page load and improving the page performance.

Dynamic component is created using the $A.createComponent()

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

Let’s understand the parameters from the above syntax:

type: The type of component to create; for example, “lightning:button”.

attributes: A map of attributes for the component, including the local Id (aura:id).

callback(cmp, status, errorMessage): The callback to invoke after the component is created.

The callback has three parameters:

cmp: The component that was created. This parameter enables you to do something with the new component, such as add it to the body of the component that creates it. If there’s an error, cmp is null.

status: The status of the call. The possible values are SUCCESS, INCOMPLETE, or ERROR. Always check that the status is SUCCESS before you try to use the component.

errorMessage: The error message if the status is ERROR.


$A.createComponent() Example:

Let’s see dynamic component creation in action.

Please create an Aura Component with the name – MyDynamicComponent and save the following the code into it.

In this example we will be creating a dynamic aura component – c:MyUtilComponent.

This custom component we have created in the previous part – Aura Component Util Methods

<aura:component>
    
    <lightning:button variant="neutral" label="Create Dynamic Components" title="Create Dynamic Components" onclick="{! c.handleDynamicComponents }"/>
    {!v.body}
</aura:component>	
({
    handleDynamicComponents : function(component, event, handler) {
        $A.createComponent(
            "c:MyUtilComponent",
            {
                "message": "This message is set dynamically during dynamic component creation"
            },
            function(comp, status, errorMessage){
                //Add the new card to the body array
                if (status === "SUCCESS") {
                    var body = component.get("v.body");
                    body.push(comp);
                    component.set("v.body", body);
                }
                else if (status === "INCOMPLETE") {
                    console.log("No response from server or client is offline.")
                    // Show offline error
                }
                else if (status === "ERROR") {
                    console.log("Error: " + errorMessage);
                    // Show error message
                }
            }
        );
    }
})

In the above component mark up, c:MyDynamicComponent contains a {!v.body} expression. When we use cmp.set(“v.body”, …) to set the component body, we must explicitly include {!v.body} in our component markup.

Below is the output when you will preview the c:MyDynamicComponent in an Aura App:

Creating Dynamic Nested Components:

To dynamically create a component in the body of another component, use $A.createComponents() to create the components.

In the function callback, nest the components by setting the inner component in the body of the outer component.

In the below example, we are creating a aura:text component in the body of a lightning:card component.

<aura:component>
    
    <lightning:button variant="neutral" label="Create Dynamic Components" title="Create Dynamic Components" onclick="{! c.handleDynamicComponents }"/>
    {!v.body}
</aura:component>	
({
    doInit : function(component, event, handler) {
        $A.createComponents([
            [
                "lightning:card",
                {
                    "aura:id": "myCard",
                    "title": "MyDynamicComponent"
                }
            ],
            [
                "aura:text",
                {
                    "value" : "This is a plain text which is dynamically nested in the card component!",
                    
                }
            ]
        ],
        function(components, status, errorMessage){
                //Add the new card to the body array
                if (status === "SUCCESS") {
                    var card = components[0];
                    var text = components[1];
                    card.set("v.body", text);
                    component.set("v.body", card);
                }
                else if (status === "INCOMPLETE") {
                    console.log("No response from server or client is offline.")
                    // Show offline error
                }
                else if (status === "ERROR") {
                    console.log("Error: " + errorMessage);
                    // Show error message
                }
            }
        );
    }
})

Below is the output when you preview the c:MyDynamicComponent from an Aura App.

Destroying Dynamically Created Components:

After a component that is declared in markup is no longer in use, the framework automatically destroys it and frees up its memory.

If you create a component dynamically in JavaScript and don’t add it to a facet like v.body or another attribute of type Aura.Component[], you have to destroy it manually.

Use Component.destroy() to destroy the component and free up its memory to avoid memory leaks.

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *