Javascript 如何在 Angular 中使用 ngFor 循环对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45819123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:13:56  来源:igfitidea点击:

How to loop over object properties with ngFor in Angular

javascriptangulartypescriptecmascript-6

提问by Jaime Rios

this is post is about an interesting problem I found at work.

这是一篇关于我在工作中发现的有趣问题的帖子。

If you don't know it yet. I'm talking about Angular 2+

如果你还不知道。我说的是 Angular 2+

The problem

问题

So you want to display the markup for a list, the values for this list come from the back end and for some reason instead of a good old array of objects you receive something like this.

所以你想显示一个列表的标记,这个列表的值来自后端,出于某种原因,你收到这样的东西而不是一个很好的旧对象数组。

    { 
  "car" : 
    { 
       "color" : "red",
       "model" : "2013"
    },
   "motorcycle": 
    { 
       "color" : "red",
       "model" : "2016"
    },
   "bicycle": 
    { 
       "color" : "red",
       "model" : "2011"
    }
}

Then you try to use *ngFor but a wild error message appears:

然后您尝试使用 *ngFor ,但会出现一条错误消息:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

You might fix it in the back end so you get an array of objects, but ain't no body got time for that. Don't you worry child, I've got us.

您可能会在后端修复它,以便您获得一组对象,但并不是没有人有时间这样做。别担心孩子,我有我们。

回答by danday74

In Angular 6.1 the KeyValuePipe was introduced which allows you to iterate object properties:

在 Angular 6.1 中引入了 KeyValuePipe,它允许您迭代对象属性:

<div *ngFor="let item of object | keyvalue">
  {{item.key}}:{{item.value}}
</div>

Docs: https://angular.io/api/common/KeyValuePipe

文档:https: //angular.io/api/common/KeyValuePipe

回答by Michele Federici

I don't know if this is safe, but for these simple cases i don't like the pipe solution, so i usually use:

我不知道这是否安全,但对于这些简单的情况,我不喜欢管道解决方案,所以我通常使用:

<div *ngFor="let k of objectKeys(yourObject)">
    {{yourObject[k].color}}
</div>

and in the controller:

并在控制器中:

objectKeys(obj) {
    return Object.keys(obj);
}

This is a quite frequent case, i don't understand why there isn't a standard implementation for this like in Angular.js 1.x

这是一个很常见的情况,我不明白为什么没有像 Angular.js 1.x 那样的标准实现

回答by EldarGranulo

A better solution would be to use a pipe such as this one:

更好的解决方案是使用这样的管道:

import { Pipe, PipeTransform } from '@angular/core';

/**
 * Convert Object to array of keys.
 */
@Pipe({
  name: 'appProperties'
})
export class PropertiesPipe implements PipeTransform {

  transform(value: {}): string[] {

    if (!value) {
      return [];
    }

    return Object.keys(value);
  }
}

Then in your template:

然后在您的模板中:

<div *ngFor="let property of response | appProperties">
    <div *ngFor="let item of response[property]">
         {{item.something}}
    </div>
</div>

回答by ChamodyaDias

    <div *ngFor="let item of donation_list | keyvalue">
        <div class="donation-box">
             <Label class="donation-label">Date : {{item.value.PaymentDate}}</Label>
             <Label class="donation-label">Time : {{item.value.PaymentTime}}</Label>

        </div>
   </div>

If you have more properties inside the object, you can use like this.

如果对象内部有更多属性,则可以这样使用。

回答by Oleg

Use Object.values to get a regular array from your object. Object.keys seems like a lot of unnecessary work.

使用 Object.values 从对象中获取常规数组。Object.keys 似乎有很多不必要的工作。

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

回答by Jaime Rios

The solution

解决方案

In a perfect world, you would get an array of objects, since the world is not always, perfect. What you want to do, is to store all those objects within an array. Here is an over-simplified solution in plain old JavaScript.

在完美的世界中,您会得到一系列对象,因为世界并不总是完美的。您想要做的是将所有这些对象存储在一个数组中。这是一个在普通旧 JavaScript 中过度简化的解决方案。

Step 1.Get all the object keys. using Object.keys. This method returns an array of a given object's own enumerable properties.

步骤 1.获取所有对象键。使用 Object.keys。此方法返回给定对象自己的可枚举属性的数组。

Step 2.Create an empty array. This is an where all the properties are going to live, since your new ngFor loop is going to point to this array, we gotta catch them all.

步骤 2.创建一个空数组。这是所有属性都将存在的地方,因为您的新 ngFor 循环将指向该数组,我们必须将它们全部捕获。

Step 3.Iterate throw all keys, and push each one into the array you created.

步骤 3.迭代 throw 所有键,并将每个键推送到您创建的数组中。

Here's how that looks like in code.

这是代码中的样子。

// Evil response in a variable. Here are all my vehicles.
let evilResponse = { 
  "car" : 
    { 
       "color" : "red",
       "model" : "2013"
    },
   "motorcycle": 
    { 
       "color" : "red",
       "model" : "2016"
    },
   "bicycle": 
    { 
       "color" : "red",
       "model" : "2011"
    }
}
// Step 1. Get all the object keys.
let evilResponseProps = Object.keys(evilResponse);
// Step 2. Create an empty array.
let goodResponse = [];
// Step 3. Iterate throw all keys.
for (prop of evilResponseProps) { 
    goodResponse.push(evilResponseProps[prop]);
}

Then you can assign the goodResponse to the class property you were trying to iterare trough in the first place.

然后,您可以将 goodResponse 分配给您首先尝试迭代的类属性。

That's all folks.

这就是所有的人。