如果我使用单击事件,那么我可以在组件中获取它的值吗
“assign(id)”函数?
你应该能够做到这一点。用@ViewChild(正如我在下面写的那样)抓住你的桌子,但在此之前,设置模板变量 - <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 将返回对 link1 节点的引用。因此,您可以使用 parentElement 属性或类似属性在 HTML 树中向上移动并获取 id。您还应该能够直接从点击处理程序传递父级,例如 function(event.target.parentElement)
如果要创建一个全新的表并附加它,逻辑是相同的:
// 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 抓取您的父元素并将该表附加到它上面。使用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 以了解有关其方法和属性的更多信息。