对于如何在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中有任何内建的管道来做同样的事情吗?


当前回答

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

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

在typescript文件中,包括:

import * as _ from 'lodash';

在导出的组件中,包括:

_: any = _;

其他回答

你现在必须这样做,我知道不是很有效的,因为你不想转换你从firebase接收的对象。

    this.af.database.list('/data/' + this.base64Email).subscribe(years => {
        years.forEach(year => {

            var localYears = [];

            Object.keys(year).forEach(month => {
                localYears.push(year[month])
            });

            year.months = localYears;

        })

        this.years = years;

    });

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

创建管道/钥匙。有内容的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>

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

更新

在6.1.0-beta.1KeyValuePipe是https://github.com/angular/angular/pull/24319引入的

<div *ngFor="let item of {'b': 1, 'a': 1} | keyvalue">
  {{ item.key }} - {{ item.value }}
</div>

砰砰作响的例子

之前的版本

另一种方法是创建NgForIn指令,如下所示:

<div *ngFor="let key in obj">
   <b>{{ key }}</b>: {{ obj[key] }}
</div>

砰砰作响的例子

ngforin.directive.ts

@Directive({
  selector: '[ngFor][ngForIn]'
})
export class NgForIn<T> extends NgForOf<T> implements OnChanges {

  @Input() ngForIn: any;

  ngOnChanges(changes: NgForInChanges): void {
    if (changes.ngForIn) {
      this.ngForOf = Object.keys(this.ngForIn) as Array<any>;

      const change = changes.ngForIn;
      const currentValue = Object.keys(change.currentValue);
      const previousValue = change.previousValue ? Object.keys(change.previousValue) : undefined;
      changes.ngForOf =  new SimpleChange(previousValue, currentValue, change.firstChange);

      super.ngOnChanges(changes);
    }
  }
}

将演示类型更改为数组 或者迭代你的对象并推到另一个数组

public details =[];   
Object.keys(demo).forEach(key => {
      this.details.push({"key":key,"value":demo[key]);
    });

从html:

<div *ngFor="obj of details">
  <p>{{obj.key}}</p>
  <p>{{obj.value}}</p>
  <p></p>
</div>

谢谢管道,但我必须做一些改变之前,我可以在angular 2 RC5使用它。更改了管道导入行,并在键数组初始化中添加了any类型。

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

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