Onclick for checkbox in typescript generates error

62 views Asked by At

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!

1

There are 1 answers

2
Paulo H. Tokarski Glinski On

There are two major problems with your code:

  1. Inserting dynamic code through innerHTML won't allow you to use event binding. Event binding only works with the template defined in your component;

  2. 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):

  1. Use *ngFor in your template instead of innerHTML:

     <table>
     <thead>
         <th>Input</th>
     </thead>
     <tbody>
         <tr *ngFor="let item of items">
             <input type='checkbox' (click)='toggleSelection()'>
         </tr>
     </tbody>
    
  2. Create a public property in your component. I called it items:

    public items: any = [];

  3. Change your generateTable() function. You only need to push new items to the items list and your template will automatically be updated. You can add your business rules here as well.

    generateTable(): void { this.items.push(1); }