问题描述
我一直在研究,发现可以使用以下代码对对象使用* ngFor:
I've been digging around, and found out that I can use the following to use *ngFor over an object:
<div *ngFor="#obj of objs | ObjNgFor">...</div>
其中ObjNgFor
管道为:
@Pipe({ name: 'ObjNgFor', pure: false })
export class ObjNgFor implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
但是,当我有一个这样的对象时:
However, when I have an object like this:
{
"propertyA":{
"description":"this is the propertyA",
"default":"sth"
},
"propertyB":{
"description":"this is the propertyB",
"default":"sth"
}
}
我不太确定如何提取"propertyA"和"propertyB",以便可以从* ngFor指令访问它们.有什么想法吗?
I am not quite sure how I can extract 'propertyA' and 'propertyB', so that it is accessible from the *ngFor directive. Any ideas?
更新
我想做的是呈现以下HTML:
What I want to do, is to present the following HTML:
<div *ngFor="#obj of objs | ObjNgFor" class="parameters-container">
<div class="parameter-desc">
{{SOMETHING}}:{{obj.description}}
</div>
</div>
等于propertyA
和propertyB
的地方(这就是对象的结构).因此,这将导致:
Where something would be equal to propertyA
and propertyB
(this is how the object is structured). So, this would lead to:
propertyA:this is the propertyA
propertyB:this is the propertyB
推荐答案
更新
在 6.1.0-beta.1 中引入了KeyValuePipe
https://github.com/angular/angular/pull/24319
<div *ngFor="let item of {'b': 1, 'a': 1} | keyvalue">
{{ item.key }} - {{ item.value }}
</div>
Plunker Example
以前的版本
您可以尝试这样的事情
export class ObjNgFor implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => Object.assign({ key }, value[key]));
}
}
然后在您的模板上
<div *ngFor="let obj of objs | ObjNgFor">
{{obj.key}} - {{obj.description}}
</div>
这篇关于如何使用* ngFor迭代对象键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!