ngFor local variables

We use the ngFor directive so often that it’s easy to forget or even ignore some of its most powerful features.

For instance, it’s fairly common to access the index of an item in the array we’re working with, but there are actually five more local variables than can be used:

  • index: number: The index of the current item in the iterable.
  • count: number: The length of the iterable.
  • first: boolean: True when the item is the first item in the iterable.
  • last: boolean: True when the item is the last item in the iterable.
  • even: boolean: True when the item has an even index in the iterable.
  • odd: boolean: True when the item has an odd index in the iterable.

The syntax to use those local variables is as follows – and you can use as many as you want in a single ngFor directive like so:

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.