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

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

问题描述

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

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

如果您还不知道。我在谈论Angular 2 +

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

问题

所以你想要要显示列表的标记,此列表的值来自后端,并且由于某种原因而不是您收到类似的旧对象数组。

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

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

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.

推荐答案

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

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>

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

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

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