Angular 2 How to use ngfor


The ngFor directive is used by Angular2 to instantiate a template once for every item in an iterable object. This directive binds the iterable to the DOM, so if the content of the iterable changes, the content of the DOM will be also changed.

Unordered list example

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

More complext template example

<div *ngFor="let item of items">

Tracking current interaction example

<div *ngFor="let item of items; let i = index">
  <p>Item number: {{i}}</p>    

In this case, i will take the value of index, which is the current loop iteration.

Angular2 aliased exported values

Angular2 provides several exported values that can be aliased to local variables. These are:

  • index
  • first
  • last
  • even
  • odd

Except index, the other ones take a Boolean value. As the previous example using index, it can be used any of these exported values:

<div *ngFor="let item of items; let firstItem = first; let lastItem = last">
  <p *ngIf="firstItem">I am the first item and I am gonna be showed</p>
  <p *ngIf="firstItem">I am not the first item and I will not show up :(</p>
  <p *ngIf="lastItem">But I'm gonna be showed as I am the last item :)</p>

*ngFor with pipe

import { Pipe, PipeTransform } from '@angular/core';
  name: 'even'

export class EvenPipe implements PipeTransform {
    transform(value: string): string {
        if(value && value %2 === 0){
          return value;

      selector: 'example-component',
      template: '<div>
                      <div *ngFor="let number of numbers | even">

export class exampleComponent {
    let numbers : List<number> = Array.apply(null, {length: 10}).map(, Number)