首页 > 解决方案 > Angular如何在QueryList中找到哪个元素被点击

问题描述

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

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

组件.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"     

}

标签: angulartypescript

解决方案


<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>

In you .ts file

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

推荐阅读