access key and value of object using *ngFor

As in latest release of Angular (v6.1.0) , Angular Team has added new built in pipe for the same named as keyvalue pipe to help you iterate through objects, maps, and arrays, in the common module of angular package.
For example –

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

To keep original order, use keyvalue:onCompare,
and in component define callback:

// ...
import {KeyValue} from '@angular/common';

@Component(/* ... */)
export class MyComponent {
  private onCompare(_left: KeyValue<any, any>, _right: KeyValue<any, any>): number {
    return -1;
  }
}

Working Forked Example

check it out here for more useful information –

If you are using Angular v5 or below or you want to achieve using pipe follow this answer

Leave a Comment