Iterate over object in Angular [duplicate]

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.

Leave a Comment