Iterate over object in Angular

It appears they do not want to support the syntax from ng1.

According to Miško Hevery (reference):

Maps have no orders in keys and hence they iteration is unpredictable. This was supported in ng1, but we think it was a mistake and will not be supported in NG2

The plan is to have a mapToIterable pipe

<div *ngFor"var item of map | mapToIterable">

So in order to iterate over your object you will need to use a "pipe". Currently there is no pipe implemented that does that.

As a workaround, here is a small example that iterates over the keys:

Component:

import {Component} from 'angular2/core';

@Component({
  selector: 'component',
  templateUrl: `
       <ul>
       <li *ngFor="#key of keys();">{{key}}:{{myDict[key]}}</li>
       </ul>
  `
})
export class Home {
  myDict : Dictionary;
  constructor() {
    this.myDict = {'key1':'value1','key2':'value2'};
  }

  keys() : Array<string> {
    return Object.keys(this.myDict);
  }
}

interface Dictionary {
    [ index: string ]: string
}

Angular 6.1.0+ Answer

Use the built-in keyvalue-pipe like this:

<div *ngFor="let item of myObject | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

or like this:

<div *ngFor="let item of myObject | keyvalue:mySortingFunction">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

where mySortingFunction is in your .ts file, for example:

mySortingFunction = (a, b) => {
  return a.key > b.key ? -1 : 1;
}

Stackblitz: https://stackblitz.com/edit/angular-iterate-key-value

You won't need to register this in any module, since Angular pipes work out of the box in any template.

It also works for Javascript-Maps.

Tags:

Angular