簡體   English   中英

如何在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 ]
})

有關更多詳細信息,請參見此問題:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM