I am generating checkboxes in a table (typescript) as follows:
generateTable(): void {
var table = document.getElementById("table1") as HTMLTableElement;
if (table.childElementCount == 2) {
for (var x = 0; x < 2; x++) {
var newRow = table.insertRow(x+1);
var newCell = newRow.insertCell(0);
newCell.innerHTML = "<input type='checkbox' onclick='toggleSelection()'>";
}
}
}
toggleSelection() {
console.log("Test");
}
Now, as soon as I click on either of the checkboxes, I receive the following console error:
Uncaught ReferenceError: toggleSelection is not defined at HTMLInputElement.onclick ((index):142:2)
I am not sure how to handle this error. It seems like the function "toggleSelection" is not properly defined. Help is very much appreciated!
There are two major problems with your code:
Inserting dynamic code through
innerHTMLwon't allow you to use event binding. Event binding only works with the template defined in your component;You should not use
onclick. Instead, you should use Angular’s event binding(click). This allows Angular to call the function defined in your component.With that in mind, I would recommend some changes in your code to make it work (it’ just a suggested approach):
Use
*ngForin your template instead ofinnerHTML:Create a public property in your component. I called it
items:public items: any = [];Change your
generateTable()function. You only need to push new items to theitemslist and your template will automatically be updated. You can add your business rules here as well.generateTable(): void { this.items.push(1); }