相当于Angular2中的ng-repeat获取JSON对象的key [英] Equivalent to ng-repeat in Angular2 to get the keys of JSON object

查看:31
本文介绍了相当于Angular2中的ng-repeat获取JSON对象的key的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用 Angular2 将 JSON 对象浏览到 HTML 页面的方法.为了得到每个键和每个值.

在 AngularJS 中,可以使用指令 ng-repeat:

{{key}}

但是在 Angular2 中,我没有找到这样做的好方法.

这是我的对象:

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

我只想分别获取键和值.我知道它可以用 Object.keys() 执行,但如果可能的话,我想使用这些指令.

谢谢!

解决方案

您可以创建一个自定义管道来执行此操作

@Pipe({name: 'toKeyValueList'})导出类 ToKeyValueListPipe 实现 PipeTransform {变换(值:数字,参数:字符串[]):任何{return//将映射转换为键和值列表}}

{{pair.key}} - {{pair.value}}</div>

你应该缓存结果,如果输入没有改变,输出不应该改变,否则 Angular 在调试模式下会产生错误消息.

不要忘记将管道添加到 @Component() 注释的 pipes: [ToKeyValueListPipe] 中你想使用它的地方.

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 !

解决方案

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.

这篇关于相当于Angular2中的ng-repeat获取JSON对象的key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆