I've been trying to add a (click) event on a cell in a dynamically generated table.
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;
};
When I do this, I get this error :
'setAttribute' on 'Element': '(click)' is not a valid attribute name.
How could I add this event, provided I need to generate that table ?
Feel free to ask for more details if needed.
Here is how I solved it:
Template :
<table>
<tr *ngFor="let row of columns">
<td *ngFor="let cell of rows" (click)="log(row+cell)"></td>
</tr>
</table>
Component :
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);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With