简体   繁体   English

如何在angular2中使用ngFor

[英]How to ngFor in angular2

I have this set of data that i want to use in one of my ng2 projects: 我有一组要在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"
      }
  ],
}

Getting this data into ng1 was easy, I was doing something like this: 将此数据导入ng1很容易,我正在做以下事情:

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

but angular2 doesn't support angular1 syntax, and solutions found don't work for me (some pipes). 但是angular2不支持angular1语法,因此找到的解决方案对我不起作用(某些管道)。 Rather that finding and pasting something randomly, can anyone help me to fully understand what I have to do here? 宁愿随机查找和粘贴某些东西,没有人可以帮助我完全理解我在这里要做的事情吗?

You could create a custom pipe for this: 您可以为此创建一个自定义管道:

@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;
  }
}

And use it like that: 并像这样使用它:

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

Don't forget to add the pipe in the pipes attribute of your component: 不要忘记将管道添加到组件的pipes属性中:

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

See this question for more details: 有关更多详细信息,请参见此问题:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM