对于如何在angular2中使用*ngFor迭代对象时获取对象的键和值,我有点困惑。我知道角1。X有一个语法

ng-repeat="(key, value) in demo"

但是我不知道如何在angular2中做同样的事情。我也做过类似的尝试,但没有成功:

    <ul>
      <li *ngFor='#key of demo'>{{key}}</li>
    </ul>

    demo = {
        'key1': [{'key11':'value11'}, {'key12':'value12'}],
        'key2': [{'key21':'value21'}, {'key22':'value22'}],
      }

以下是我的尝试: http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview

如何使用*ngFor动态获取key1和key2 ?经过广泛的搜索,我发现了使用管道的想法,但我不知道如何去做。 在angar2中有任何内建的管道来做同样的事情吗?


当前回答

和Angular的最新版本(v6.1.0)一样,Angular团队在Angular package的公共模块中添加了与keyvalue管道同名的内置管道,以帮助你迭代对象、映射和数组。 例如:

<div *ngFor="let item of testObject | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

要保持原来的顺序,使用keyvalue:onCompare, 在组件中定义回调:

// ...
import {KeyValue} from '@angular/common';

@Component(/* ... */)
export class MyComponent {
  private onCompare(_left: KeyValue<any, any>, _right: KeyValue<any, any>): number {
    return -1;
  }
}

工作分叉示例

点击这里查看更多有用的信息

https://github.com/angular/angular/blob/master/CHANGELOG.md#features-3 https://github.com/angular/angular/commit/2b49bf7

如果你使用的是Angular v5或更低版本,或者你想使用管道实现,请遵循这个答案

使用ngfor获取对象的访问键和值

其他回答

如果你已经在使用Lodash,你可以使用这个简单的方法,包括键和值:

<ul>
  <li *ngFor='let key of _.keys(demo)'>{{key}}: {{demo[key]}}</li>
</ul>

在typescript文件中,包括:

import * as _ from 'lodash';

在导出的组件中,包括:

_: any = _;

这里没有一个答案对我有用,下面是对我有用的:

创建管道/钥匙。有内容的Ts:

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

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform
{
    transform(value:any, args:string[]): any {
        let keys:any[] = [];
        for (let key in value) {
            keys.push({key: key, value: value[key]});
        }
        return keys;
    }
}

添加到app.module.ts(你的主模块):

import { KeysPipe } from './pipes/keys';

然后向模块声明数组中添加如下内容:

@NgModule({
    declarations: [
        KeysPipe
    ]
})
export class AppModule {}

然后在你的视图模板中,你可以使用这样的东西:

<option *ngFor="let entry of (myData | keys)" value="{{ entry.key }}">{{ entry.value }}</option>

如果你想读更多,这里是我找到的一个很好的参考资料。

在其他优秀的管道中,有一个非常好的库可以做到这一点。它叫做ngx管道。

例如,keys管道返回对象的键,values管道返回对象的值:

钥匙管

<div *ngFor="let key of {foo: 1, bar: 2} | keys">{{key}}</div> 
<!-- Output: 'foo' and 'bar -->

价值管

<div *ngFor="let value of {foo: 1, bar: 2} | values">{{value}}</div>
<!-- Output: 1 and 2 -->

不需要创建自己的自定义管道:)

使用指数:

<div *ngFor="let value of Objects; index as key">

用法:

{{key}} -> {{value}}

这里有一个简单的解决方案

你可以为此使用typescript迭代器

import {Component} from 'angular2/core';
declare var Symbol;
@Component({
    selector: 'my-app',
    template:`<div>
    <h4>Iterating an Object using Typescript Symbol</h4><br>
Object is : <p>{{obj | json}}</p>
</div>
============================<br>
Iterated object params are:
<div *ngFor="#o of obj">
{{o}}
</div>

`
})
export class AppComponent {
  public obj: any = {
    "type1": ["A1", "A2", "A3","A4"],
    "type2": ["B1"],
    "type3": ["C1"],
    "type4": ["D1","D2"]
  };

  constructor() {
    this.obj[Symbol.iterator] =  () => {
          let i =0;

          return {
            next: () => {
              i++;
              return {
                  done: i > 4?true:false,
                  value: this.obj['type'+i]
              }
            }
          }
    };
  }
}

http://plnkr.co/edit/GpmX8g?p=info