angular6 - 如何在角度 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(){
???
}
解决方案
在内部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));
}
}
更新
如果您想在 Angular 6、7 和 8 中进行这项工作,您可以使用document.getElementById('tableId')
而不是使用ViewChild
.
请看看这个StackBlitz
推荐阅读
- java - 我如何计算每个省有多少男性和女性,并且这些省按国家字母顺序排列?
- javascript - 在 javascript 中执行 http 请求响应
- php - 在 GCP App Engine 上安装 PHP 扩展
- r - R - 删除除最近日期以外的所有行?
- lua - 桌面模拟器中的 LUA 脚本
- regex - DFA 到 RE 的转换但是如果初始状态和最终状态相同怎么办?
- javascript - 在功能 cartNumbers 我收到此错误:Cannot set property 'textContent' of null at cartNumbers
- javascript - 将 if 语句脚本添加到电子表格的新行
- html - 如何使用 HTML CSS 在登录表单中创建弹出窗口?
- nuxt.js - 使用 IISNode 在 IIS 中部署 NUXT JS 应用程序