Implement something like *ngFor of angular using Vanilla js .


Hi everyone .

If you have used Angular you must be familiar with *ngFor tag and how easy it makes to render ui elements dynamically.

In this article we will see how we can achieve similar thing in vanilla js .

For this tutorial I will be using CodeSandBox for creating vanilla js and angular project.

Angular approach

first we will create an array it will contain elements which we will be rendered in the html.



As you can see i have an array with five elements . Now I will use *ngFor to run a loop on this to render elements .




here we are running a loop in html file and creating button elements with value as that of the array.

It gives us 5 buttons .




Now we will try to make something very similar in vanilla js.

to achieve this dynamic behaviour we will write html in string format and bind it to innerHtml of desired DOM element .


we have two variables here one contains array elements like we did in angular.
second variable will be used to store html in string format.



this is our html file , we will target div with id app to add five buttons as it's innerHtml.

To create buttons as per the array items we will loop through it and store the html in btnHtml variable.


we have used a forEach loop to iterate through the array items on line 5.
on line 6 you can notice html for button inside a div is written in string format and is assigned to innerHtml of element with id 'app' on like 9.


this gives us similar result as that of what we got in Angular.

repo link for vanlla-js.
repo link for angular







Comments

Popular posts from this blog

Making service call in Angular

How to Git ? Make you first push ?