【问题标题】:Angular how to find which element in QueryList<ElementRef> is clickedAngular 如何查找 QueryList<ElementRef> 中的哪个元素被点击
【发布时间】:2020-09-17 15:15:12
【问题描述】:

我有一组使用 ViewChildren 的表格单元格(动态创建的 td html 元素)的 ElmentRef(QueryList)。我已调试并有可用的元素集。

当我点击一个特定的 td html 元素时,我调用了一个函数,在该函数中我需要找到 ElementRef(QueryList) 中的哪个元素被点击。我该怎么做?

component.html

<table>

    <tr *ngFor="let i of Arr">
      <ng-container *ngFor="let j of Arr">
      
      <td  #tdID (click)="cellClicked(tdID)">
       
      </td>
      </ng-container>
    
    </tr>
    </table>

组件.ts

Arr =[1,2,3];
 @ViewChildren('tdID') divs:QueryList<ElementRef>;

cellClicked(cell) {
       console.log("Cell clicked"+cell);
//Help find here which element in the divs QueryList matches "cell"     

}

【问题讨论】:

  • ngFor 循环中有 ij 变量;也将它们传递给单元格单击功能。这样,您就知道了单元格的“坐标”。
  • 是的,这会有所帮助,只是看看是否有任何直接的方法。

标签: angular typescript


【解决方案1】:
<table>
    <tr *ngFor="let i of Arr">
      <ng-container *ngFor="let j of Arr">

      <td  #tdID (click)="cellClicked(tdID, i, j)">

      </td>
      </ng-container>

    </tr>
</table>

在你的 .ts 文件中

cellClicked(tdID, i, j) {
   console.log(tdID, i, j)
}

【讨论】:

  • 是的,这也是 R Richards 的建议。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 2018-01-24
  • 2022-11-13
  • 2018-04-26
相关资源
最近更新 更多