Create and destroy lightning components dynamically

Hey Users,

Sometimes our component markup code gets too bigger that we cannot write child components markup in the same parent. That makes our code too lengthy to write and understand. One better approach is to dynamically create the components which we want to use, append them to our parent body and destroy them when their work is done to free memory again. This approach is more efficient and memory saving.

Dynamic component creation is easy to write and use. You can call your custom component or native lightning components. You can also create HTML tags dynamically and append them to any div of your choice. So, let’s create a component dynamically.

Why create a component dynamically?
Creating components dynamically will make your code more efficient and modular. You can dynamically create any component and destroy it when it is done. This will save memory and prevent memory leaks.

Method-1: Create a native lightning component dynamically

We will create a lightning:button dynamically and append it to the div.

dynamic creation lightning component

Step-1: Create a div in the parent component. [DynamicCreation.cmp]

Step-2: Create lightning component and append it to div. [DynamicCreationController.js]

 

Method-2: Create a custom component dynamically

Here, we will create a custom lightning modal first and then we will call this modal dynamically in another component.

 

dynamic lightning component creation

Step-1: Create a child component. [Child.cmp]

Step-1: Destroy child on cancel button click. [ChildController.js]

Step-3: Create a div in parent component where you want to append your child component.

[Parent.cmp]

Step-4: Create child component dynamically and append it to div. [ParentController.js]

Step-5: Call Parent controller.

 

Method-3: Create an HTML tag dynamically

To create HTML tags dynamically, we will use aura:html tag. Aura:html can create any html tag.

 

dynamic html tag creation in lightning

Step-1: Create a div in the parent component. [DynamicCreation.cmp]

Step-2: Create HTML tag dynamically and append it to div. [DynamicCreationController.js]

 

Our dynamic component creation is now ready to use. Go ahead and optimize your code.

You can destroy your dynamically created component by the child as well as the parent too. Click the link below to know more.

Cheers ……..:)

 

Leave a Reply

avatar
  Subscribe  
Notify of