【发布时间】:2018-08-26 21:46:51
【问题描述】:
我正在尝试找到将一些指令和事件添加到生成的表格元素及其子元素的最佳方法。
我正在以编程方式在 typescript 中创建一个表格
document.createElement('table')
然后我添加tHead 等等...
在我的<tr> 上,我想添加(click)="doSomething()",原因很明显。
我必须使用 EventListeners 还是有不同/更好的方法? 我还需要在一些东西上添加一个 *ngIf。不完全确定如何去做。
感谢您为我指明方向的任何建议!
编辑 抱歉我的描述性不是很好。下面是我的表创建功能。它使用递归。这就是我不使用标记的原因。除非有一种简单的方法可以使用指令进行递归。
buildTable(tableData: any, properties: string[], tableId: string, tableClass: string): HTMLTableElement {
let table = document.createElement('table');
// setting attribute and class if they are passed in
if (tableId) {
table.setAttribute('id', tableId);
}
if (tableClass) {
table.classList.add(tableClass);
}
// create table header with reference
let tHeader = table.createTHead();
// Create the header row with reference
let headerRow = tHeader.insertRow(0);
headerRow.classList.add('table-header');
// Fill header with data
for (let x = 0; x < properties.length; x++) {
let th = document.createElement('th');
th.innerHTML = properties[x];
headerRow.appendChild(th);
}
// create table body with reference
let tBody = table.createTBody();
// dictionary for properties with nested data
let subData: { [key: string]: any; };
for (let x = 0; x < tableData.length; x++) {
subData = {}; // clear nested data
let row = tBody.insertRow();
row.classList.add('table-row');
let rowData = tableData[x];
properties.forEach(prop => {
let cell = row.insertCell();
// Does this property have nested data?
if (Array.isArray(rowData[prop])) {
cell.innerHTML = prop;
subData[prop] = rowData[prop];
// build the sub table row, cell, and child table
Object.keys(subData).forEach(key => {
// sub table row
let subRow = tBody.insertRow();
subRow.classList.add('sub-content');
// sub row that holds the table
let subCell = subRow.insertCell();
subCell.setAttribute('colspan', properties.length.toString());
subCell.appendChild(this.buildTable(subData[key], Object.keys(subData[key][0]), null, 'sub-table'));
});
}
else {
cell.innerHTML = rowData[prop];
}
});
}
return table;
}
这会按预期创建表。我现在需要添加事件以显示/隐藏子表并单击行以选择要编辑/删除/任何数据的数据。这通常是(click)="doSomething()"
【问题讨论】:
标签: angular typescript events angular5 angular2-directives