如何在angular2中使用ngFor

How to ngFor in angular2

我有这组数据想用在我的一个 ng2 项目中:

{
  "Administration et gestion": [
    {
        "id": "1_1",
        "text": "Assistance comptable"
    },
    {
        "id": "1_2",
        "text": "Conseil fiscal et impots"
    },
    {
        "id": "1_3",
        "text": "Conseil juridique"
    },
    {
        "id": "1_4",
        "text": "Conseil auto-entrepreneur"
    }
  ],
  "Animaux": [
    {
        "id": "2_1",
        "text": "garde d'animaux"
    },
    {
        "id": "2_2",
        "text": "toitellage"
    }
  ],
  "Enfants": [
      {
          "id": "3_1",
          "text": "baby-sitting"
      },
      {
          "id": "3_2",
          "text": "aides au devoirs"
      }
  ],
}

将这些数据导入 ng1 很容易,我正在做这样的事情:

ng-repeat="(key, skill) in skills"

但是 angular2 不支持 angular1 语法,并且找到的解决方案对我不起作用(某些管道)。与其随机查找和粘贴一些东西,谁能帮助我完全理解我必须在这里做什么?

您可以为此创建自定义管道:

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

然后像那样使用它:

<div *ngFor="#keyValue of skills | keys">
  <div>{{keyValue.key}}<div>
  <div *ngFor="#value of keyValue.value">
    {{value.id}} = {{value.text}}
  </div>
</div>

不要忘记在组件的 pipes 属性中添加管道:

@Component({
  (...)
  pipes: [ KeysPipe ]
})

有关详细信息,请参阅此问题:

  • Invalid argument for pipe 'AsyncPipe'