如何在angular2中使用ngFor [英] How to ngFor in angular2

查看:98
本文介绍了如何在angular2中使用ngFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this set of data that i want to use in one of my ng2 projects:

{
  "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的数据很简单,我做的是这样的:

Getting this data into ng1 was easy, I was doing something like this:

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

但angular2不支持angular1语法,找到的解决方案对我不起作用(某些管道)。相反,随机找到并粘贴一些东西,任何人都可以帮我完全理解我在这里要做的事情吗?

but angular2 doesn't support angular1 syntax, and solutions found don't work for me (some pipes). 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;
  }
}

并使用它:

<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:

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

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

See this question for more details:

  • Invalid argument for pipe 'AsyncPipe'

这篇关于如何在angular2中使用ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆