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.

  1. type—The type of component to create; for example, “ui:button”.
  2. attributes—A map of attributes for the component, including the local Id (aura:id).
  3. 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.

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.

The dynamic lightning component will be an option in case if you wanted to create lightning components dynamically by using client-side javascript.