Dynamic Creation of Aura Components
We can create aura components dynamically in the lightning framework by calling the ‘$A.createComponent()’ method to create a component from your javascript code.
The ‘$A.createComponent()’ Method
This method follows the following syntax :
$A.createComponent(String type, Object attributes, function callback)
Where,
- type: The type of component to create; for example, “lightning:input”.
- attributes: A map of attributes for the component, including the aura:id and other attributes like label..
- callback: The callback to invoke after the component is created.
The callback has three supported parameters and follows the following syntax :
callback(cmp, status, errorMessage)
cmp: The component which was created dynamically. We can use this ‘cmp’ to add this component to the markup. If there’s an error in creation,the value of ‘cmp’ is null.
status: The status returned in a string. If the status is SUCCESS then the component was created successfully, if we got an ERROR in the status then the call failed.
errorMessage: If the status was ERROR then the error message is returned in this parameter, otherwise this is blank.
Example Usage
Here is an example which dynamically creates a lightning input in the aura component’s markup. We define an attribute of the ‘aura.component’ type to be used in inserting the new lightning input to the markup.
Markup:
<aura:component> <aura:attribute type="Aura.Component[]" name="panel"/>{!v.panel} <lightning:button label="Create Component" onclick="{!c.createComponent}"/> </aura:component>
Javascript Controller : ({ createComponent : function(cmp, event, helper) { $A.createComponent( "lightning:input", { "aura:id": "input-id", "label": "Press Me First" }, function(newField, status, errorMessage){ if (status === "SUCCESS") { var panel = cmp.get("v.panel"); panel.push(newField); cmp.set("v.panel", panel); } } ); } })
The output of the above is like this :
And once we press this button, the new lightning field is generated and added to the markup :
The call back function pushes the new field to the ‘panel’ attribute which can take any type of aura component as input to add it to the markup.
We can also create custom aura components like this instead of standard components as well.
And lastly, we can also call the ‘destroy()’ method in order to destroy an aura component from the markup as well.