如何获取单击angular2的当前索引

时间:2017-04-17 20:49:03

标签: angular

使用angular2可以获得点击时的当前*ngFor索引值吗? 我有一个客户列表,我想得到他们的索引值。

<button ion-item *ngFor="let customer of customers" (click)="showRadio()">
    {{ customer.customer_name }}
</button>
  showRadio(currentIndex) {
  //................    

  for(var j=0; j<myResult[currentIndex].bookingIds.length; j++) {
    alert.addInput({
      type: 'radio',
      label: myResult[currentIndex].bookingIds[j],
      value: myResult[currentIndex].bookingIds[j],
      checked: false
    });

  }

enter image description here

3 个答案:

答案 0 :(得分:7)

我已经找到了解决方案。只需让let i = index并将i设置为函数内的参数。

<button ion-item *ngFor="let customer of customers; let i = index" (click)="showRadio(i)">

信用:youtube

答案 1 :(得分:7)

ngFor指定

index将设置为每个模板上下文的当前循环迭代。

所以你需要这样做:

 <button ion-item *ngFor="let customer of customers; let i = index;" (click)="showRadio()">
          {{ i }} - {{ customer.customer_name }}
 </button>

答案 2 :(得分:0)

您可以在客户对象中包含索引,然后在函数

中传递它
[{"customer_index":1,"customer_name":"jason"},
 {"customer_index":2,"customer_name":"mary"}];

然后在函数

中传递它
<button ion-item *ngFor="let customer of customers" (click)="showRadio(customer.customer_index)">
            {{ customer.customer_name }}
    </button>
相关问题