遍历Angular中的对象 [英] Iterate over object in Angular

查看:411
本文介绍了遍历Angular中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Angular 2 Alpha 28中做一些事情,并且字典和NgFor遇到了问题.

I am trying to do some things in Angular 2 Alpha 28, and am having an issue with dictionaries and NgFor.

我在TypeScript中有一个如下所示的界面:

I have an interface in TypeScript looking like this:

interface Dictionary {
    [ index: string ]: string
}

在JavaScript中,这将转换为带有数据的对象,看起来像这样:

In JavaScript this will translate to an object that with data might look like this:

myDict={'key1':'value1','key2':'value2'}

我想对此进行迭代并尝试以下操作:

I want to iterate over this and tried this:

<div *ngFor="(#key, #value) of myDict">{{key}}:{{value}}</div>

但无济于事,以下任何一项都不起作用:

But to no avail, none of the below worked either:

<div *ngFor="#value of myDict">{{value}}</div>
<div *ngFor="#value of myDict #key=index">{{key}}:{{value}}</div>

在所有情况下,我都会收到意外令牌"或找不到'iterableDiff'管道支持对象"之类的错误

In all cases I get errors like "Unexpected token" or "Cannot find 'iterableDiff' pipe supporting object"

我在这里想念什么?这不可能了吗? (第一种语法在Angular 1.x中有效)还是在对象上进行迭代时语法不同?

What am I missing here? Is this not possible anymore? (The first syntax works in Angular 1.x) or is the syntax different for iterating over an object?

推荐答案

看来他们不想支持ng1的语法.

It appears they do not want to support the syntax from ng1.

根据MiškoHevery(参考):

According to Miško Hevery (reference):

地图在键中没有顺序,因此它们的迭代是不可预测的. ng1支持此功能,但我们认为这是一个错误,并且不会 在NG2中受支持

Maps have no orders in keys and hence they iteration is unpredictable. This was supported in ng1, but we think it was a mistake and will not be supported in NG2

计划要有一个mapToIterable管道

The plan is to have a mapToIterable pipe

<div *ngFor"var item of map | mapToIterable">

因此,要遍历对象,您将需要使用管道". 当前,没有实现此操作的管道.

So in order to iterate over your object you will need to use a "pipe". Currently there is no pipe implemented that does that.

作为一种解决方法,下面是一个迭代键的小示例:

As a workaround, here is a small example that iterates over the keys:

组件:

import {Component} from 'angular2/core';

@Component({
  selector: 'component',
  templateUrl: `
       <ul>
       <li *ngFor="#key of keys();">{{key}}:{{myDict[key]}}</li>
       </ul>
  `
})
export class Home {
  myDict : Dictionary;
  constructor() {
    this.myDict = {'key1':'value1','key2':'value2'};
  }

  keys() : Array<string> {
    return Object.keys(this.myDict);
  }
}

interface Dictionary {
    [ index: string ]: string
}

这篇关于遍历Angular中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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