Writing For Loops In Angular With ngFor Directive

In the previous post, we looked at how we can display dynamic values in the Angular Component into our Views with the help of Interpolation. In this post, we will look at how we can mix Interpolation with one of the most powerful programming concepts “For Loop“. Writing For Loops in Angular is quite easy and is possible with the help of ngFor directive.

Basic Syntax Of Writing For Loops In Angular

ngFor works by allowing you to repeat a template with each item of a list. The basic syntax for writing for loops in angular is this:

<div *ngFor="let item of items">
{{ item }}
</div>

As you can guess by looking at the code, we are iterating over the list of “items” and displaying it’s value using Interpolation technique.

A Simple Demo

Let’s make use of ngFor loop.

We have a list of “developers ” object as below:

developers = [
{developer: “Mr Joe”},
{developer:”Miss Janice”},
{developer:”Mr Karkey”}
];

Now if we want to display this list to our users, we can write something like this in our View:

Here are our developers:

<ul *ngFor="let person of developers">

<li>Developer: {{ person.developer }}</li>

</ul>
This will result in the following view:
Writing For Loops In Angular With ngFor

Writing For Loops In Angular With ngFor

All the values of the “developers” object are displayed using the ngFor directive and Intepolation technique.

Getting Current Index

We can also get the index of the current iterating item using ngFor. The index could be useful in cases where you need to do something with the nth value of the list. Or simply if you would like to change the CSS property, getting the value of index can be useful.

You can get the value of current index in the following manner:

<ul *ngFor="let person of developers; let i = index;">

When we are writing for loops in angular, we can also assign a local variable to first, last, even, and odd values. These are all boolean values that default to true or false based on the current iteration.

Update your code to something like below and see what you get in the view.

<ul *ngFor="let person of developers; let isOdd = odd;">

<li>

<strong *ngIf="isOdd">I am Odd </strong>

Developer : {{ person.developer }}

</li>

</ul>

 

  • Leave a Reply