Angular ngFor Built-In Directive

Angular ngFor built-in directive is used to iterate an array or an object, which helps to display each item value in the array. Here now we going to create an HTML template with ul li and using that we loop the value.

Basic Angular ngFor Directive

Now you going to see basic ngFor directive. With the quickstart, we going to repeat the HTML li tag with each value in the loop. Below you have the example, open the app.component.ts and add the below code.

The above ngFor directive will display the HTML element with display a single user of the users collection. Here we looping each user array and execute the users name list.

Display in HTML

If you like to display in app.component.html or somewhere which would you like? It is simple, instead of using the template you can use in .html extension, like the below code.

Output:

Basic Angular ngFor Directive

Index Angular ngFor Directive

If you like to get the index of the particular user’s element? by adding another variable in our ngFor we going to get the index value, below you have an example.

The index always starts from 0 but here you can see the index will start from 1 because here we declared the index variable as 1, so it starts from 1.

Output:

Index Angular ngFor Directive

Grouping Angular ngFor Directive

If you like to get the group of data and display it with the ngFor directive? here below you can see by a group of the location we can get both data and display the values by using two ngFor directives. Use the below code in app.component.ts

Now open the app.component.html and add the below code, here we used two ngFor one for locations another users list and index value for each user by locations.

Output:

Grouping Angular ngFor Directive

Conclusion:

I believe this article helps you out from what is ngFor and how it works. If you like this article share it with your friends or if you have any questions use the below comment box.

Was this article helpful?

Yes No
×

How can we improve it?

×

We appreciate your helpul feedback!

Your answer will be used to improve our content. The more feedback you give us, the better our pages can be.

Follow us on social media:

Facebook Pinterest

Mraj

Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts.

Leave a Reply

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

Back to top