(单击)事件在 ANGULAR 4 中附加任何数据时不起作用

(click) event not working while append any data in ANGULAR 4

虽然我试图附加“tr 标签”(点击)事件在 angular 4 中不起作用,但这是我的代码。

$('#time_table_table tbody').append('<tr data-id="1"><td>Sunday<a (click)="assign(1)">Assign</a></td></tr>');

当我在“assign()”函数中尝试“console.log(id)”时,它不会打电话。

if i am use click Event then can i get it's value in Component in "assign(id)" function?

你应该可以做到。使用@ViewChild 获取您的 table(正如我在下面所写),但在此之前,设置模板变量 - <table #myTable...@ViewChild('myTable') myTable:ElementRef;,然后通过渲染器创建所需的元素 - let tr1 = this.rd.createElement("tr");let td1 = this.rd.createElement("td");let link1 = this.rd.createElement("a"); ,使用 createText 方法创建文本节点,使用 appendChild 将它们附加到相应的 HTML 节点,并使用 listen() 方法添加点击处理程序 - this.rd.listen(link1, 'click', function(event.target))event.target 将 return 引用到 link1 节点。因此,您可以使用 parentElement 属性 或类似的方法在 HTML 树中向上移动并获取 ID。您还应该能够直接从点击处理程序传递父项,例如 function(event.target.parentElement)


如果你想创建一个全新的 table 并追加它,逻辑是一样的:

// Create header row and append to table:
let table = this.rd.createElement("table");  
let tr1 = this.rd.createElement("tr");  
let tr1Th1 = this.rd.createElement("th");  
let tr1Text = this.rd.createText("Name")
this.rd.appendChild(table, tr1);
this.rd.appendChild(tr1, tr1Th1);
this.rd.appendChild(tr1Th1, tr1Text);

// add body row:
let tr2 = this.rd.createElement("tr");  
let tr2Td1 = this.rd.createElement("td");  
let tr2Text = this.rd.createText("John")
this.rd.appendChild(table, tr2);
this.rd.appendChild(tr2, tr2Td1);
this.rd.appendChild(tr2Td1, tr2Text);

看起来有点难看,但是如果你从你的ComponentClass做,我不知道其他方法。之后使用 @ViewChild 获取您的父元素并将 table 附加到它。使用 setAttribute 方法添加属性。要改进代码,您可以使用一些循环或函数式编程技术。


Angular 并非设计用于直接与 DOM 一起使用,因此 jQuery 是一个糟糕的选择。在 Angular,这些天,我们使用 Renderer2。

现在在您的问题中,您首先需要获取 #time_table_table tbody 元素的引用。首先想到的可能是简单地使用 ElementRef:

constructor(el: ElementRef) {
  el.nativeElement.querySelector('#time_table_table tbody');
}

但是您不应该使用 ElementRef 来修改DOM。对于此类任务,您可以使用 @ViewChild()。它接受一个字符串参数,该参数是模板变量的名称。所以 @ViewChild('myDiv') el:ElementRef 查询将引用 <div #myDiv> Foo </div>.

这里有一个例子,你可以怎么做:

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

export class MyComponent implements OnInit {
  @ViewChild('yourVariable') el:ElementRef;

constructor(private rd: Renderer2){

ngOnInit() {   
  let btn = this.rd.createElement("button");  
  let text = this.rd.createText("Click")
  this.rd.appendChild(btn, text);
  this.rd.appendChild(this.el.nativeElement, btn)

  this.rd.listen(btn, "click", () => console.log(1));
}

您阅读了 Renderer2 以了解有关其方法和属性的更多信息。