Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate dictionary in angular template?

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

like image 435
Krishnan Avatar asked Mar 01 '18 10:03

Krishnan


2 Answers

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

<span *ngFor="let item of content | keyvalue">           
  Key: {{item.key}}, Value: {{item.value}}
</span>
like image 93
Frederik Struck-Schøning Avatar answered Nov 17 '22 08:11

Frederik Struck-Schøning


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>
like image 38
Ofek Amram Avatar answered Nov 17 '22 07:11

Ofek Amram