等效于Angular2中的ng-repeat以获取JSON对象的键 [英] Equivalent to ng-repeat in Angular2 to get the keys of JSON object
问题描述
我正在寻找一种使用Angular2将JSON对象浏览到HTML页面的方法.为了获得每个键和每个值.
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.
在AngularJS中,可以使用指令ng-repeat
:
In AngularJS, it's possible with the directive ng-repeat
:
<div ng-repeat="(key, data) in dataSets">{{key}}</div>
但是在Angular2中,我找不到找到这样的好方法.
But in Angular2, i don't find a good way to do like this.
这是我的对象:
Object {name: "Rue Saint-Nestor", oneway: "yes", highway: "residential", maxspeed: "50", source:maxspeed: "FR:urban"}
我只想分别获取键和值.
我知道它可能与Object.keys()
一起执行,但我想尽可能使用这些指令.
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.
谢谢!
推荐答案
您可以创建执行此操作的自定义管道
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>
您应该缓存结果,以便,如果输入未更改,输出也不应更改,否则Angular在调试模式下会产生错误消息.
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.
不要忘记将管道添加到要使用的@Component()
注释的pipes: [ToKeyValueListPipe]
中.
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对象的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!