ECMA 2017+ solution
Following the idea of some other answers, you can create a Pipe to create an array of [key, value] from your object, but in a much simpler way, following the new method Object.entries introduced in the ECMA 2017.
Pipe
import { PipeTransform, Pipe } from '@angular/core'; /** * Transform a literal object into array */ @Pipe({ name: 'forObject', pure: true, }) export class ForObjectPipe implements PipeTransform { transform(object, args?: any): any { return Object.entries(object); } }
Module
In your module, you declare and provide it
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ForObjectPipe } from './for-object.pipe'; import { MyPageRoutingModule } from './my-routing.module'; import { MyPage } from './my.page'; @NgModule({ imports: [ CommonModule, MyPageRoutingModule, ], declarations: [ MyPage, ForObjectPipe, ], providers: [ ForObjectPipe, ] }) export class MyPageModule {}
Then you can use in your component typescript code or HTML.
Using in component
// ... import { ForObjectPipe } from './for-object.pipe'; @Component({ selector: 'app-my', templateUrl: './my.page.html', styleUrls: ['./my.page.scss'], }) export class MyComponent { obj: { [key: any]: any } = { 1: 'hello', 2: 'world', }; constructor(private forObjectPipe: ForObjectPipe) { } foo() { const myArray = this.forObjectPipe.transform(this.obj); // same as const myArray = Object.entries(this.obj); } }
Using in component view
<h1>Object:</h1> <div *ngFor="let pair of obj | forObject"> KEY: {{ pair[0] }} - VALUE: {{ pair[1] }} </div>
Output:
Object: KEY: 1 - VALUE: hello KEY: 2 - VALUE: world
Live Demo: https://stackblitz.com/edit/angular-qapapx?file=src/app/hello.component.ts
key, valuepair kind of syntax in angular2ngFor, you should look at this answerPipefor this..