3

I'm looking for a way to browse a JSON object into an HTML page with Angular2. In order to get each keys and each values.

In AngularJS, it's possible with the directive ng-repeat:

<div ng-repeat="(key, data) in dataSets">{{key}}</div>

But in Angular2, i don't find a good way to do like this.

This is my object :

Object {name: "Rue Saint-Nestor", oneway: "yes", highway: "residential",   maxspeed: "50", source:maxspeed: "FR:urban"}

I just want get the keys and values separately. I know it may be perform with Object.keys() but I want to use the directives if it's possible.

Thanks !

1 Answers1

4

You can create a custom pipe that does that

@Pipe({name: 'toKeyValueList'})
export class ToKeyValueListPipe implements PipeTransform {
  transform(value:number, args:string[]) : any {
    return // transform map to a list of keys and values
  }
}
<div *ngFor="let pair in dataSets | toKeyValueList">{{pair.key}} - {{pair.value}}</div>

You should cache the result so, if the input hasn't changed the output shouldn't change otherwise Angular produces an error message in debug mode.

Don't forget to add the pipe to the pipes: [ToKeyValueListPipe] of the @Component() annotation where you want to use it.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567