Create HTML tags dynamically in lightning

cafeforce
cafeforce 1.8k Views Add a Comment
dynamic html tags creation

Sometimes lightning components are slow and bigger to use in our parent code. The replacement of a few simple lightning components are HTML tags. A lightning component is made up of many things and consists of many properties. If you want a use a simpler version of code, better to use an HTML tag/component. That makes our code light.

But what if we want a component to appear when needful and destroy when the work is done. 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 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.

Working Demo:

dynamic html tag creation in lightning

Step-1: Create the DynamicHTMLCreation lightning component.

For creating a new lightning component navigate to Developer Console > File > New > Lightning Component

Enter Name & Description and click Submit. Now component markup file will open by default. In the right sidebar, click on Controller to create JS Controller too.

In the DynamicHTMLCreation.cmp , paste the below code.

Step-2: Add dynamic creation code to the JS controller.

open the controller file DynamicHTMLCreationController.js and paste the below code.

Step-3: Now we will call the component.

Here we go, our component is ready to use now. Whenever you need to add multiple components or components in iteration, you can always create them dynamically and destroy them when the work is done.

Also, Check – Create and Destroy Lightning components Dynamically.

Cheers & Happy Coding … 🙂

 

 

Share This Article
Leave a comment
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments