How to loop over object properties with ngFor in Angular
In Angular 6.1 the KeyValuePipe was introduced which allows you to iterate object properties:
<div *ngFor="let item of object | keyvalue"> {{item.key}}:{{item.value}}</div>
I don't know if this is safe, but for these simple cases i don't like the pipe solution, so i usually use:
<div *ngFor="let k of objectKeys(yourObject)"> {{yourObject[k].color}}</div>
and in the controller:
objectKeys(obj) { return Object.keys(obj);}
This is a quite frequent case, i don't understand why there isn't a standard implementation for this like in Angular.js 1.x
A better solution would be to use a pipe such as this one:
import { Pipe, PipeTransform } from '@angular/core';/** * Convert Object to array of keys. */@Pipe({ name: 'appProperties'})export class PropertiesPipe implements PipeTransform { transform(value: {}): string[] { if (!value) { return []; } return Object.keys(value); }}
Then in your template:
<div *ngFor="let property of response | appProperties"> <div *ngFor="let item of response[property]"> {{item.something}} </div></div>