Rickard Staaf Rickard Staaf - 1 year ago 1664
TypeScript Question

Iterate over TypeScript Dictionary in Angular 2

I am trying to do some things in Angular 2 Alpha 28, and am having an issue with dictionaries and NgFor.

I have an interface in TypeScript looking like this:

interface Dictionary {
[ index: string ]: string

In JavaScript this will translate to an object that with data might look like this:


I want to iterate over this and tried this:

<div *ngFor="(#key, #value) of myDict">{{key}}:{{value}}</div>

But to no avail, none of the below worked either:

<div *ngFor="#value of myDict">{{value}}</div>
<div *ngFor="#value of myDict #key=index">{{key}}:{{value}}</div>

In all cases I get errors like "Unexpected token" or "Cannot find 'iterableDiff' pipe supporting object"

What am I missing here? Is this not possible anymore? (The first syntax works in Angular 1.x) or is the syntax different for iterating over an object?

Answer Source

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:


import {Component} from 'angular2/core';

  selector: 'component',
  templateUrl: `
       <li *ngFor="#key of keys();">{{key}}:{{myDict[key]}}</li>
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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download