Equivalent to ng-repeat in Angular2 to get the keys of JSON object [duplicate]

做~自己de王妃 提交于 2019-12-20 02:26:20

问题


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:


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.



来源:https://stackoverflow.com/questions/35317513/equivalent-to-ng-repeat-in-angular2-to-get-the-keys-of-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!