11

In our angular application, from controller I have returned a dictionary. How can I display the same in html template using *ngFor?

Please anyone help to achieve the same

Krishnan
  • 1,012
  • 1
  • 15
  • 30
  • Possible duplicate of [Iterate over object in Angular](https://stackoverflow.com/questions/31490713/iterate-over-object-in-angular) – aloisdg Oct 12 '18 at 14:47

2 Answers2

39

You can use the built-in keyvalue pipe like this:

<span *ngFor="let item of content | keyvalue">           
  Key: {{item.key}}, Value: {{item.value}}
</span>
Frederik Struck-Schøning
  • 12,471
  • 8
  • 59
  • 64
8

You can create a pipe that maps the object (dictionary) to an array containing of type : { key: string,value: any }

Somthing like this:

@Pipe({name: 'mapToArray'})
export class MapToArray implements PipeTransform {
  transform(value, args:string[]) : any {
    let arr = [];
    for (let key in value) {
      arr.push({key: key, value: value[key]});
    }
    return arr;
  }
}

and use it like that in the html file:

<span *ngFor="let item of content | mapToArray">           
  Key: {{item.key}}, Value: {{item.value}}
</span>
Frederik Struck-Schøning
  • 12,471
  • 8
  • 59
  • 64
Ofek Amram
  • 452
  • 2
  • 6