如何使用 *ngFor 迭代对象键? [英] How to iterate object keys using *ngFor?

查看:42
本文介绍了如何使用 *ngFor 迭代对象键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在挖掘,发现我可以使用以下内容在对象上使用 *ngFor:

 <div *ngFor="#obj of objs | ObjNgFor">...</div>

其中 ObjNgFor 管道是:

@Pipe({ name: 'ObjNgFor', pure: false })导出类 ObjNgFor 实现 PipeTransform {变换(值:任何,参数:任何[] = null):任何{返回 Object.keys(value).map(key => value[key]);}}

但是,当我有这样的对象时:

<代码>{属性A":{"description":"这是属性A",默认":某事"},属性B":{"description":"这是物业B",默认":某事"}}

我不太确定如何提取propertyA"和propertyB",以便可以从 *ngFor 指令访问它们.有什么想法吗?

更新

我想要做的是呈现以下 HTML:

 

<div class="参数描述">{{某事}}:{{obj.description}}

某物等于 propertyApropertyB(这就是对象的结构).所以,这将导致:

propertyA:这是propertyA属性B:这是属性B

解决方案

更新

6.1.0-beta.1 中引入了 KeyValuePipe https://github.com/angular/angular/pull/24319

{{ item.key }} - {{ item.value }}

Plunker 示例

以前的版本

你可以试试这样的

导出类 ObjNgFor 实现 PipeTransform {变换(值:任何,参数:任何[] = null):任何{return Object.keys(value).map(key => Object.assign({ key }, value[key]));}}

然后在你的模板上

 

{{obj.key}} - {{obj.description}}

Plunker

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>

where ObjNgFor pipe is:

@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"
 }
}

I am not quite sure how I can extract 'propertyA' and 'propertyB', so that it is accessible from the *ngFor directive. Any ideas?

UPDATE

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>

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

解决方案

Update

In 6.1.0-beta.1 KeyValuePipe was introduced https://github.com/angular/angular/pull/24319

<div *ngFor="let item of {'b': 1, 'a': 1} | keyvalue">
  {{ item.key }} - {{ item.value }}
</div>

Plunker Example

Previous version

You could try something like this

export class ObjNgFor implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value).map(key => Object.assign({ key }, value[key]));
    }
}

And then on your template

  <div *ngFor="let obj of objs | ObjNgFor">
   {{obj.key}} - {{obj.description}}
  </div>

Plunker

这篇关于如何使用 *ngFor 迭代对象键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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