首页 > 解决方案 > 如果按钮来自Angular中的列表,那么识别按下按钮的最佳方法是什么?

问题描述

我有一个项目列表,我正在使用 *ngFor 显示这些项目。而且我在每个迭代的独立项目上都有一个带有功能的按钮。代码如下。

 <ul *ngFor="let data of datas">

//                 . . .

                <button
                  type="button"
                  class="btn btn-secondary btn-circle btn-sm"
                  (click)="showDetail(**parameter**)"
                  >  show
                </button>
//                 . . .

这是我的表演功能。我不知道在这个参数中传递什么。

increment(**parameter**) {
    console.log(this.data[**parameter**]['price']);
  }

我想显示特定选定项目的价格。我的数据列表如下。

[
      { id: "1111", guest: "abc", price: 20 },
      { id: "222", guest: "xyz", price: 30 }    ]

标签: htmlangular

解决方案


您可以data作为参数发送

<ul *ngFor="let data of datas">
...
  <button type="button" class="btn btn-secondary btn-circle btn-sm" (click)="showDetail(data)">  
      show
   </button>
...
</ul>


increment(data) {
  console.log(data.price);
}

或者你可以发送index

<ul *ngFor="let data of datas; let i = index">
...
  <button type="button" class="btn btn-secondary btn-circle btn-sm" (click)="showDetail(i)">  
      show
   </button>
...
</ul>


increment(index) {
  console.log(this.data[index]['price']);
}

推荐阅读