How to iterate object keys using *ngFor How to iterate object keys using *ngFor angular angular

How to iterate object keys using *ngFor


Angular 6.0.0

https://github.com/angular/angular/blob/master/CHANGELOG.md#610-2018-07-25

introduced a KeyValuePipe

See also https://angular.io/api/common/KeyValuePipe

@Component({  selector: 'keyvalue-pipe',  template: `<span>    <p>Object</p>    <div *ngFor="let item of object | keyvalue">      {{item.key}}:{{item.value}}    </div>    <p>Map</p>    <div *ngFor="let item of map | keyvalue">      {{item.key}}:{{item.value}}    </div>  </span>`})export class KeyValuePipeComponent {  object: {[key: number]: string} = {2: 'foo', 1: 'bar'};  map = new Map([[2, 'foo'], [1, 'bar']]);}

original

You can use a pipe

@Pipe({ name: 'keys',  pure: false })export class KeysPipe implements PipeTransform {    transform(value: any, args: any[] = null): any {        return Object.keys(value)//.map(key => value[key]);    }}
<div *ngFor="let key of objs | keys">

See also How to iterate object keys using *ngFor?


I think the most elegant way to do that is to use the javascript Object.keys like this (I had first implemented a pipe for that but for me, it just complicated my work unnecessary):

in the Component pass Object to template:

Object = Object;

then in the template:

<div *ngFor="let key of Object.keys(objs)">   my key: {{key}}   my object {{objs[key] | json}} <!-- hier I could use ngFor again with Object.keys(objs[key]) --></div>

If you have a lot of subobjects you should create a component that will print the object for you. By printing the values and keys as you want and on an subobject calling itselfe recursively.

Hier you can find an stackblitz demo for both methods.


I know this question is already answered but I have one solution for this same.

You can also use Object.keys() inside of *ngFor to get required result.

I have created a demo on stackblitz. I hope this will help/guide to you/others.

CODE SNIPPET

HTML Code

<div *ngFor="let key of Object.keys(myObj)">  <p>Key-> {{key}} and value is -> {{myObj[key]}}</p></div>

.ts file code

Object = Object;myObj = {    "id": 834,    "first_name": "GS",    "last_name": "Shahid",    "phone": "1234567890",    "role": null,    "email": "test@example.com",    "picture": {        "url": null,        "thumb": {            "url": null        }    },    "address": "XYZ Colony",    "city_id": 2,    "provider": "email",    "uid": "test@example.com"}