我一直在尝试在动态生成的表格中的单元格上添加(点击)事件。
HTMLtoAdd:any;
@Input() roles:string;
ngOnInit() {
let alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
let table = document.createElement('table');
for (let i=0;i<10;i++){
let newRow = document.createElement('tr');
for (let j=0;j<10;j++) {
let newCell = document.createElement('td');
let cellId = alphabet[i]+j;
newCell.setAttribute("id",cellId);
newCell.setAttribute("(click)","alert(this.id)");
newRow.appendChild(newCell);
}
table.appendChild(newRow);
}
this.HTMLtoAdd = table.outerHTML;
};
当我这样做时,我收到此错误:
'setAttribute' on 'Element': '(click)' is not a valid attribute name.
如果需要生成该表,我该如何添加此事件?
如果需要,请随时询问更多详细信息。
答案 0 :(得分:4)
以下是我解决它的方法:
模板:
<table>
<tr *ngFor="let row of columns">
<td *ngFor="let cell of rows" (click)="log(row+cell)"></td>
</tr>
</table>
组件:
columns:string[]=[];
rows:number[]=[];
ngOnInit() {
let gridSize = 10;
for (let i=0; i<gridSize;i++){
this.columns.push(String.fromCharCode(65+i));
};
for (let i=0; i<gridSize;i++){
this.rows.push(i);
}
};