如何在 Angular 中使用 ngFor 循环对象属性 [英] How to loop over object properties with ngFor in Angular

查看:25
本文介绍了如何在 Angular 中使用 ngFor 循环对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章是关于我在工作中发现的一个有趣问题.

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

问题

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

<代码> {车" :{红色",型号":2013"},摩托车":{红色",型号":2016"},自行车":{红色",型号":2011"}}

然后你尝试使用 *ngFor 但出现了一个疯狂的错误信息:

找不到类型为object"的不同支持对象[object Object]".NgFor 仅支持绑定到可迭代对象,例如数组.

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

解决方案

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

{{item.key}}:{{item.value}}

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

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+

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:

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.

解决方案

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

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

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

这篇关于如何在 Angular 中使用 ngFor 循环对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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