For-each in ionic2 with angularjs2

时光总嘲笑我的痴心妄想 提交于 2019-12-12 07:58:37

问题


I make one application with IONIC-2 Beta version. I want to use for-each loop. is it possible to use for each in angular-V2?

Thanks.


回答1:


First in the Component, you have to declare the array you want to show:

import { Component } from "@angular/core";

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  displayData : [];

  constructor() {
    this.displayData = [
      {
        "text": "item 1",
        "value": 1
      },
      {
        "text": "item 2",
        "value": 2
      },
      {
        "text": "item 3",
        "value": 3
      },
      {
        "text": "item 4",
        "value": 4
      },
      {
        "text": "item 5",
        "value": 5
      },
    ];
  }
}

If you want to change the values in the code, you can do it by doing:

// We iterate the array in the code
for(let data of this.displayData) {
  data.value = data.value + 5;
}

And then in your View you can print them like this:

<ion-content class="has-header">
  <ion-list *ngFor="let data of displayData; let i = index" no-lines>
    <ion-item>Index: {{ i }} - Text: {{ data.text }} - Value: {{ data.value }}</ion-item>
  </ion-list>
</ion-content>

Please notice that part *ngFor="let data of displayData" where:

  • displayData is the array we defined in the Component
  • let data of ... defines a new variable called data, which represents each of the elements of the displayData array.
  • we can access the properties for each array element by using that data variable, and interpolation like {{ data.propertyName }}.


来源:https://stackoverflow.com/questions/38524761/for-each-in-ionic2-with-angularjs2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!