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


当前回答

我认为是客体。钥匙是这个问题的最佳解决方案。对于任何遇到这个答案并试图找出为什么Object的人。Keys给他们['0','1']而不是['key1', 'key2'],这是一个警示性的故事-注意“of”和“in”之间的区别:

我已经在使用Object了。键,类似于这个:

interface demo {
    key: string;
    value: string;
}

createDemo(mydemo: any): Array<demo> {
    const tempdemo: Array<demo> = [];

    // Caution: use "of" and not "in"
    for (const key of Object.keys(mydemo)) {
        tempdemo.push(
            { key: key, value: mydemo[key]}
        );
    }

    return tempdemo;
}

然而,与其

for (const key OF Object.keys(mydemo)) {

我无意中写了

for (const key IN Object.keys(mydemo)) {

哪个“工作”完全正常,没有任何错误并返回

[{key: '0', value: undefined}, {key: '1', value: undefined}]

这花了我2个小时在谷歌上搜索和咒骂。

(打了额头上)

其他回答

和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获取对象的访问键和值

有对象。在*ngFor中使用它。

@Component({
  selector: 'app-myview',
  template: `<div *ngFor="let key of objectKeys(items)">{{key + ' : ' + items[key]}}</div>`
})

export class MyComponent {
  objectKeys = Object.keys;
  items = { keyOne: 'value 1', keyTwo: 'value 2', keyThree: 'value 3' };
  constructor(){}
}

ECMA 2017+解决方案

遵循一些其他答案的思想,您可以创建一个Pipe来从您的对象创建一个[key, value]数组,但是以一种更简单的方式,遵循新的方法object。在ECMA 2017中引入的条目。

Pipe

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

/**
 * Transform a literal object into array
 */
@Pipe({
  name: 'forObject',
  pure: true,
})
export class ForObjectPipe implements PipeTransform {

  transform(object, args?: any): any {
    return Object.entries(object);
  }
}

模块

在模块中,声明并提供它

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ForObjectPipe } from './for-object.pipe';

import { MyPageRoutingModule } from './my-routing.module';
import { MyPage } from './my.page';

@NgModule({
  imports: [
    CommonModule,
    MyPageRoutingModule,
  ],
  declarations: [
    MyPage,
    ForObjectPipe,
  ],
  providers: [
    ForObjectPipe,
  ]
})
export class MyPageModule {}

然后你可以在你的组件中使用typescript代码或HTML。

组件中使用

// ...
import { ForObjectPipe } from './for-object.pipe';

@Component({
  selector: 'app-my',
  templateUrl: './my.page.html',
  styleUrls: ['./my.page.scss'],
})
export class MyComponent {
  obj: { [key: any]: any } = {
    1: 'hello',
    2: 'world',
  };

  constructor(private forObjectPipe: ForObjectPipe) { }

  foo() {
     const myArray = this.forObjectPipe.transform(this.obj);
     // same as 
     const myArray = Object.entries(this.obj);
  }
}

在组件视图中使用

<h1>Object:</h1>
<div *ngFor="let pair of obj | forObject">
  KEY: {{ pair[0] }} - VALUE: {{ pair[1] }}
</div>

输出:

Object:
KEY: 1 - VALUE: hello
KEY: 2 - VALUE: world

现场演示:https://stackblitz.com/edit/angular-qapapx?file=src/app/hello.component.ts

在Angular 6.1中,你可以使用keyvalue管道:

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

但是它有一个不方便的地方,就是根据键值对结果列表进行排序。 如果你需要中性的东西:

@Pipe({ name: 'keyValueUnsorted', pure: false  })
export class KeyValuePipe implements PipeTransform {
  transform(input: any): any {
    let keys = [];
    for (let key in input) {
      if (input.hasOwnProperty(key)) {
        keys.push({ key: key, value: input[key]});
      }
    }
    return keys;
  }
}

不要忘记指定pure:false管道属性。在这种情况下,管道在每个更改检测周期中都被调用,即使输入引用没有更改(向对象添加属性时也是如此)。

你可以使用keyvalue管道作为示例代码提供:

    <div style="flex-direction: column">
        <app-cart-item
            class="cart-item"
            *ngFor="let keyValuePair of this.allProductRecords | keyvalue"
            [productRecord]="keyValuePair.value"
            (removeProduct)="removeProductFromCart(keyValuePair.key)"
        ></app-cart-item>
        <br />
        <p style="font-family: Verdana, Geneva, Tahoma, sans-serif; font-weight: bolder">
            Total ${{ getTotalPurchaseAmount() }}
        </p>
    </div>