12

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,030
  • 1
  • 15
  • 30

2 Answers2

45

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,981
  • 8
  • 59
  • 68
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,981
  • 8
  • 59
  • 68
Ofek Amram
  • 452
  • 2
  • 6
  • I have imported the class.I am getting the below error: The pipe 'mapToArray' could not be found. – Krishnan Mar 01 '18 at 10:51
  • 1
    you need to declare pipes just like components inside the decleration array in your module – Ofek Amram Mar 01 '18 at 11:02
  • I use this solution but get error 'error TS2554: Expected 2 arguments, but got 1' on mapToArray in html file. how to solve this error? – Hessam Hosseini Jun 02 '22 at 13:23
  • @HessamHosseini: you can change the signature of transform: transform(value, args?: any) so that args become optional. Also change the declaration of arr to : let arr : any[] = []; to prevent this error "Type 'any' is not assignable to type 'never'." – Bill Jun 09 '22 at 09:44