Dynamically Creating Lightning Components
In this post, I am going to show how to create a lightning component dynamically by using javascript controller. Create a component dynamically in your client-side JavaScript code by using the $A.createComponent() method. To create multiple components, use $A.createComponents().$A.createComponent Syntax is looking as shown below.
$A.createComponent(String type, Object attributes, function callback)
- type—The type of component to create; for example, “ui: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
In this example, The client-side controller calls $A.createComponent() to create a ui:inputText with a local ID. The function(newInp, status, errorMessage) callback appends the inputText to the body of c:createComponent.
<aura:component > <lightning:button variant="brand" label="Create Component" onclick="{! c.handleComponent }" /> {!v.body} </aura:component>
({ handleComponent : function(component, event, helper) { $A.createComponent( "ui:inputText", { "aura:id": "inpId", "labelClass":"slds-form-element__label", "placeholder":"Enter Some Text", "label": "Enter some text", "class": "slds-input" }, function(newInp, status, errorMessage){ if (status === "SUCCESS") { var body = component.get("v.body"); body.push(newInp); component.set("v.body", body); } else if (status === "INCOMPLETE") { console.log("No response from server or client is offline.") } else if (status === "ERROR") { console.log("Error: " + errorMessage); } } ); }, })
Creating 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.
<aura:component > <lightning:button variant="brand" label="Create Components" onclick="{! c.handleComponent }" /> {!v.body} </aura:component>
({ handleComponent : function(component, event, helper) { $A.createComponents([ ["ui:outputText",{ "value" :"Message1" }], ["ui:outputText",{ "value" : "Message2" }], ["ui:outputText",{ "value" :"Message3" }] ], function(components, status, errorMessage){ if (status === "SUCCESS") { var body = component.get("v.body"); components.forEach(function(item){ body.push(item); }); component.set("v.body", body); } else if (status === "INCOMPLETE") { console.log("No response from server or client is offline.") } else if (status === "ERROR") { console.log("Error: " + errorMessage); } } ); }, })
The dynamic lightning component will be an option in case if you wanted to create lightning components dynamically by using client-side javascript.