In this post we are going to go over the ngFor core directive, namely we are going to go over the following:
  • what ngFor does and what is its syntax
  • What are the most common errors associated to ngFor
  • Variable visibility
  • Finding the index position of an element
  • How to stripe a table using even and odd
  • Identifying the first and the last element of a list
  • How does ngFor track items, why it can be important for performance ?
  • How to use trackBy ?
  • When to use trackBy ?
  • Learn why ngFor is not only for arrays
  • A quick question for you at the end about learning
So let's get started diving into ngFor ! Below you can also find a video version of this post if you prefer, and the running code of this post is available here.
The ngFor features are also covered in this video, have a look:

What can we do with ngFor ?

The core directive ngFor allows us to build data presentation lists and tables in our HTML templates. Let's take for example the following data:
const HEROES = [
{id: 1, name:'Superman'},
{id: 2, name:'Batman'},
{id: 5, name:'BatGirl'},
{id: 3, name:'Robin'},
{id: 4, name:'Flash'}
];
view rawdata.ts hosted with ❤ by GitHub
With ngFor we can print this data to the screen under the form of a data table, by generating HTML similar to this:
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr>
<td>Superman</td>
</tr>
<tr>
<td>Batman</td>
</tr>
...
</tbody>
</table>
view rawtable.html hosted with ❤ by GitHub

What is the syntax of ngFor ?

To use ngFor, let's create a component so that we can have a working HTML template:
@Component({
selector:'heroes',
template: `
<table>
<thead>
<th>Name</th>
<th>Index</th>
</thead>
<tbody>
<tr *ngFor="let hero of heroes">
<td>{{hero.name}}</td>
</tr>
</tbody>
</table>
`
})
export class Heroes {
heroes = HEROES;
}
view rawcomponent.ts hosted with ❤ by GitHub
This template will generate the HTML table that we showed just above. We can see in this example the (most common) syntax for using ngFor:
  • we are passing to ngFor an iteration expression
  • a loop variable named hero is defined using the keyword let, which is consistent with Javascript syntax
  • the expression is under the form of var i of items, which is consistent with the Javascript of iteration functionality

Variable Visibility

Note that the loop variable hero is only visible inside the loop, you would not be able to access it outside the ngFor section.

Common ngFor Errors to watch out for

If you have an AngularJs background, you will see this error a few times before you get used to the new Angular syntax:
Can't bind to 'ngFor' since it isn't a known property of 'tr'
This is because you have accidentally either used item in items instead of item of items, or forgot to add the let keyword at the beginning of the expression:
<tr *ngFor=" hero in heroes">
<td>{{hero.name}}</td>
</tr>
view rawerror.html hosted with ❤ by GitHub

Finding the index of a list element

A very common requirement is to add to a list the numeric index position of its element. We can get the index of the current element by using the indexvariable:
<tr *ngFor="let hero of heroes; let i = index">
<td>{{hero.name}}</td>
<td>{{i}}</td>
</tr>
view rawngFor-index.html hosted with ❤ by GitHub
Note that you need the let keyword to get the value of the index, otherwise you will get an error similar to this one:
Parser Error: Unexpected token = at column ...
With this change, the HTML generated now looks like the following:
<table>
<thead>
<th>Name</th>
<th>Index</th>
</thead>
<tbody>
<tr>
<td>Superman</td>
<td>0</td>
</tr>
<tr>
<td>Batman</td>
<td>1</td>
</tr>
...
</tbody>
</table>
view rawtable-index.html hosted with ❤ by GitHub

How to stripe a table using even and odd

Another very common functionality needed when building tables is to be able to stripe a table by adding a different css class to the even or odd rows.
Let's say that to the above table we want to add a CSS class even if the row is even and the CSS class odd if the row is odd.
In order to so, we have a couple of variables available for that: even and odd, that can be used in the following way together with ngClass:
<tr *ngFor="let hero of heroes; let even = even; let odd = odd"
[ngClass]="{ odd: odd, even: even }">
<td>{{hero.name}}</td>
</tr>
view raweven-odd.html hosted with ❤ by GitHub
Let's have a look at the HTML generated by this template:
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr class="even">
<td>Superman</td>
</tr>
<tr class="odd">
<td>Batman</td>
</tr>
...
</tbody>
</table>
view raweven-odd-output.html hosted with ❤ by GitHub
As we can see, ngClass added the CSS classes to the right rows, as we would expect.

Identifying the first and the last element of a list

Just like the even and odd functionality, there are also two other variables that can be used to identify the first and the last elements of the list:
<tr *ngFor="let hero of heroes; let first = first; let last = last"
[ngClass]="{ first: first, last: last }">
<td>{{hero.name}}</td>
</tr>
view rawfirst-last.html hosted with ❤ by GitHub
This will add a CSS class named first to the first element of the list, and a CSS class named last to the last element of the list:
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr class='first'>
<td>Superman</td>
</tr>
...
<tr class='last'>
<td>Flash</td>
</tr>
</tbody>
</table>

How does ngFor work when we add or remove elements from the list?

As the input list gets modified, ngFor will try to avoid to constantly create and destroy the DOM elements of the list, as this is an expensive operation. Also, when we pass to ngFor a new list, this does not mean that the whole list will be re-built, meaning all the DOM re-created.
Many of the existing DOM elements will be reused and only some values inside them will be overwritten, and the decision is taken for each element in the list separately.
In order to take that decision Angular needs to identify each list element in a unique way, because for example if we pass in a new list with a different order, Angular will try to identify the elements and re-order the DOM elements of the list without deleting them and recreating them.

How are list items tracked by default ?

ngFor by default tracks list items using object identity. This means that if you build a list of new objects from scratch with the exact same values as the previous list and pass this newly built list to ngFor, Angular will not be able to tell that a given list item is already present or not.
From a point of view of object identity, the new list contains a whole new set of items, completely different from the previous set. This is the case if for example we query the data again from the backend.
Tracking by object identity is a good default strategy because Angular has no information about the object so it cannot tell which property it should use for tracking.

Why can this be important for performance?

As we see, ngFor already does a lot of optimizations out-of-the-box to try to reuse existing DOM elements as much as possible, but it's doing so based on object identity.
In the case of templates with large lists, or lists that occupy a large part of the screen, we might even with those optimizations still run into performance issues and notice that the UI is slow due to the large amount of DOM elements being created and destroyed.
If that happens to be the case, we can configure ngFor to do the tracking by something else other than object identity.

How to use trackBy ?

We can provide our own mechanism for tracking items in a list by using trackBy. We need to pass a function to trackBy, and the function takes a couple of arguments, which are an index and the current item:
@Component({
selector:'heroes',
template: `
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr *ngFor="let hero of heroes; trackBy: trackHero" >
<td>{{hero.name}}</td>
</tr>
</tbody>
</table>
`
})
export class Heroes {
heroes = HEROES;
trackHero(index, hero) {
console.log(hero);
return hero ? hero.id : undefined;
}
}
This implementation would do the tracking based on the id property.

When to use trackBy ?

The use of trackBy it's a performance optimization and is usually not needed by default, it's in principle only needed if running into performance issues.
Let's say that you are shipping to ancient mobile browsers or ancient versions of IE: you might want to consider applying trackBy as a precaution in your larger tables, but it really depends on your system and the use case.

Why is ngFor is not only For Arrays?

In this example, we have been passing to ngForan array of Javascript objects, but actually we don't necessarily need to pass in an array to ngFor in order for it to work.
We can pass to it any kind of Javascript Iterable in general, including Iterables that are created by the framework itself. To illustrate this, we are going to define a directive for a configuration element called hero:
import {Directive, Input} from "@angular/core";
@Directive({
selector: 'hero',
})
export class Hero {
@Input()
id: number;
@Input()
name:string;
}
view rawhero.ts hosted with ❤ by GitHub
We can now use this configuration element in our template in the following way:
<heroes>
<hero id="1" name="Superman"></hero>
<hero id="2" name="Batman"></hero>
<hero id="3" name="Batgirl"></hero>
<hero id="3" name="Robin"></hero>
<hero id="4" name="Flash"></hero>
<hero id="5" name="Green Lantern"></hero>
</heroes>
view rawapp.ts hosted with ❤ by GitHub
Now let's query this data from the configuration elements using @ContentChildren:
Do you see what happened here? Turns out the QueryList is a class that is part of Angular and is itself an Iterable! So although we can use it programmatically in the component class, we can also pass it directly to ngFor and iterate over it directly.