【问题标题】:How to write click event for dynamic generated table's first td value in angular 6如何在角度 6 中为动态生成表的第一个 td 值编写点击事件
【发布时间】:2019-11-26 14:59:56
【问题描述】:

我尝试为表的 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(){

???
}

【问题讨论】:

    标签: angular6 angular7 angular8


    【解决方案1】:

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

    <table #mytable ... >
    

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

    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

    【讨论】:

    • 我用适用于 Angular 6、7 和 8 的解决方案更新了我的答案
    • 更新了我的表格结构..如何在自定义表格组件中找到表格标签?
    • 和表数据也来自json
    猜你喜欢
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多