首页 > 解决方案 > 如何在角度 6 中为动态生成表的第一个 td 值编写点击事件

问题描述

我试图为表的 tr td 值编写点击事件。我已经生成了一个表并且我有 tableid。如果我单击第一列 td 值,我想显示警报。我们该怎么做?有什么解决方案吗?

请不要写任何内联 onclick 事件。我想在app.component.ts文件中写。

例子:

app.component.html

<custom-table id="tableId">
     <table>
      <thead>
        <th>Company</th>
        <th>Contact</th>
        <th>Country</th>
      </thead>
      <tr>
        <td>123456</td> ---->If i click this i want to show alert with this value
        <td>Maria Anders</td>
        <td>Germany</td>
      </tr>
      <tr>
        <td>253689</td>---->If i click this i want to show alert with this value
        <td
        <td>Francisco Chang</td>
        <td>Mexico</td>
      </tr> 
     </table>
<custom-table>

app.component.ts

ngOnInit(){

???
}

标签: angular6angular7angular8

解决方案


在内部app.component.html,将模板引用变量(使用#)添加到表元素。

<table #mytable ... >

app.component.ts中,将模板引用变量与 链接ViewChild,然后在其中安装click侦听器ngAfterViewInit

import {Component, ViewChild, AfterViewInit, ElementRef} from '@angular/core';

export class AppComponent implements AfterViewInit {

    @ViewChild('mytable', {static: false}) tableRef: ElementRef<HTMLTableElement>;

    ngAfterViewInit() {
        for (let row of this.tableRef.nativeElement.rows) {
            const firstCell = row.childNodes.item(0);
            firstCell.addEventListener('click', () => alert(firstCell.textContent));      
        }
    }

StackBlitz

更新

如果您想在 Angular 6、7 和 8 中进行这项工作,您可以使用document.getElementById('tableId')而不是使用ViewChild.

请看看这个StackBlitz


推荐阅读