Angular 10 Structural directive example





Hey guys in this post we will discuss angular structural directive ngFor. This directive will be used to loop through the items or list inside the view template. let’s look at an example.

Assume that we have an array of numbers from 1 to 10 and we need to display those numbers inside the view template.

File: app.component.ts

In order to loop through the numbers inside the view template, we will use angular structural directive ngFor. Let’s look at the syntax first.

here, we will add * to the ngFor, indicating that this is a structural directive. Next, items is the list or an array that you want to iterate. Then item, is the local reference variable will be creating with let keyword using which we will access the item/number/object




Now let’s look at the example to loop through the inside view template

File: app.component.html

This will loop through the numbers array. It also creates <p> tag which is the size of the array. Because we will be looping on the <p> tag.

We can also loop through the array of objects. let’s look at an example

File: app.component.ts

We have list of employees, each employee object having name and salary. let’s loop iterate this array of objects inside the view template.

File: app.component.html

you can see, e is the local reference variable and this will hold the single employee object. we will access the properties using dot(.)

Optionally, the ngFor provides the index of each item. let’s look at an example

you can see, inside the ngFor, after the array, we will be accessing the index of the item and will be assigning it to the local variable i.

This way we can access the index of each item.



About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *