How to ngFor in angular2

2019-09-08 10:42发布

问题:

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"
      }
  ],
}

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

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

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?

回答1:

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:

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

See this question for more details:

  • Invalid argument for pipe 'AsyncPipe'