【问题标题】:Retrieve ID of *ngFor elements in a table - Angular检索表中 *ngFor 元素的 ID - Angular
【发布时间】:2021-02-04 13:26:50
【问题描述】:

我有一个表格,其中我使用*ngForButton 标记内迭代了 3 个 FA 图标,就像这里显示的图像。

我已经为 3 个按钮提供了单独的 ID(即 1,2 和 3)来记录单击了哪个按钮。按钮是添加、编辑和删除。虽然我通过 (click) 事件将它的 ID 发送到组件。每次单击按钮时,该函数都无法检索 ID。它在随机多次单击后检索 ID,而不是每次单击按钮时检索。我不明白它为什么会这样。

HTML:

<tbody>
    <tr *ngFor="let ABC of XYZ">
      <td>{{ABC.Records}}}</td>
      <td>
           <button id="1" (click)="fun($event)"><fa-icon [icon]="plussquare"></fa-icon></button>
           <button id="2" (click)="fun($event)" ><fa-icon [icon]="editfa"></fa-icon></button>
           <button id="3" (click)="fun($event)" ><fa-icon [icon]="trashfa"></fa-icon></button>
      </td>
    </tr>
</tbody>

.TS:

fun($event:any){
     console.log($event.target.id)
 }

所有添加按钮的 id 应为 1,编辑按钮的 id 应为 2,删除按钮的 id 为 3。

【问题讨论】:

  • 不确定这是否是完整的答案,但 ID 应该是唯一的,所以如果每一行的按钮与其他行中的按钮具有相同的 ID,那将是一个问题。尝试更改 ID 以在其中也包含行号,以便表格中的每个按钮最终都有不同的 ID。
  • 即使我将value 属性设置为添加、编辑和删除,它仍然会随机检索该值。所以即使 ID 应该是 unquie,value 属性至少应该有效,但事实并非如此。
  • 为什么不好玩(ABC, ‘edit’) etc..?
  • 感谢@MikeOne,您的评论也很有魅力!

标签: html angular typescript angular-directive ngfor


【解决方案1】:

你不只需要3个方法吗?

 funEdit($event:any, yourVar){
     console.log($event.target.id)
 }
funAdd($event:any, yourVar){
         console.log($event.target.id)
}
funDelete($event:any, yourVar){
         console.log($event.target.id)
}

你会喜欢它:

<button (click)="funAdd($event,ABC)"><fa-icon [icon]="plussquare"></fa-icon></button>
<button (click)="funEdit($event,ABC)" ><fa-icon [icon]="editfa"></fa-icon></button>
<button (click)="funDelete($event,ABC)" ><fa-icon [icon]="trashfa"></fa-icon></button>
 

并在第二个参数中传递您的 ABC 变量以了解该行

【讨论】:

    猜你喜欢
    • 2019-07-05
    • 1970-01-01
    • 2023-03-15
    • 2018-02-27
    • 2021-09-10
    • 2019-03-09
    • 2018-09-10
    • 2018-07-16
    • 2019-05-04
    相关资源
    最近更新 更多