Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display json object using *ngFor

Tags:

I want to display the below data from Firebase

{    "-KBN9O_qqz-nZ9tPWFdM":{       "createdAt":1456399292790,       "isActive":true,       "name":"Hero 1"    },    "-KBN9gjJw1ZlMgt9pVsl":{       "createdAt":1456399371220,       "isActive":true,       "name":"Hero 2"    },    "-KBN9hYI4vYAsyh5k1lX":{       "createdAt":1456399374548,       "isActive":true,       "name":"Hero 3"    } } 

when doing angular.io Tour of Heroes tutorial for example

<li *ngFor="#hero of heroes">   <span class="badge">{{hero.id}}</span> {{hero.name}} </li> 

So hero id should show for example -KBN9hYI4vYAsyh5k1lX and hero name should show for example hero 3


I have done some research and come across this stackoverflow solution by @Thierry Templier access key and value of object using *ngFor

(1) Is this the right solution to my problem?

(2) Is there a simpler solution to this problem because I feel that it would be really common for developers using Angular2 to display such json data.

like image 663
Jek Avatar asked Feb 26 '16 08:02

Jek


People also ask

How do I get the key and value of an object in ngFor?

There is no inbuilt pipe or method to get key and value from the *ngFor loop. so we have to create custom pipe for the same.

Can you nest objects in JSON?

Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.


1 Answers

You need to implement a custom pipe to do this. ngFor only supports array and not object.

This pipe will look like that:

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

and use it like that:

<span *ngFor="#entry of content | keys">              Key: {{entry.key}}, value: {{entry.value}} </span> 

See this question for more details:

  • access key and value of object using *ngFor
like image 188
Thierry Templier Avatar answered Sep 22 '22 12:09

Thierry Templier