迭代打字稿字典中的2角 [英] Iterate over TypeScript Dictionary in Angular 2

查看:216
本文介绍了迭代打字稿字典中的2角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一些事情角2阿尔法28,和时遇到的词典和NgFor的问题。

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

我在打字稿的界面看起来像这样:

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 *ng-for="(#key, #value) of myDict">{{key}}:{{value}}</div>

但无济于事,没有任何的工作如下任一:

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

<div *ng-for="#value of myDict">{{value}}</div>
<div *ng-for="#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"

我缺少的是在这里吗?这是不可能的了? (第一语法角度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.

据MISKO Hevery(参考):

According to Miško Hevery (reference):

地图在钥匙没有订单,因此,他们迭代未predictable。
  这是在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

&LT; D​​IV * NG-的地图VAR项目| mapToIterable&GT;

因此​​,为了在你的对象上进行迭代,你将需要使用一个管道。
目前还没有实施了做到这一点。

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, View, NgFor} from 'angular2/angular2';

@Component({
  selector: 'component'
})
@View({
  templateUrl: `
       <ul>
       <li *ng-for="#key of keys();">{{key}}:{{myDict[key]}}</li>
       </ul>
  `,
  directives: [NgFor]
})
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
}

这篇关于迭代打字稿字典中的2角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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