Search code examples
javascripttypescriptangular7

Property rows does not exist on type HTMLElement error TS2339 when loop through table


problem

Property rows does not exist on type HTMLElement error TS2339

when loop through table on angular 7

I work on angular 7 when loop to table html and compile i get error

ERROR in src/app/Pages/part-compare/part-compare.component.ts(25,38):

error TS2339: Property 'rows' does not exist on type 'HTMLElement'.

src/app/Pages/part-compare/part-compare.component.ts(27,26): error TS2339:

Property 'rows' does not exist on type 'HTMLElement'.

How to solve this error please ?

What I have tried:

var table = document.getElementById("CompareParts");
    for (var i = 1, row; row = table.rows[i]; i++) {
      for (var j = 0, col; col = row.cells[j]; j++) {
        var Cell = table.rows[i].cells
        this.ACells.push(Cell);
      }
    }
    this.length=this.ACells.length
    for (var x = 0; x < this.ACells.length; x++) {
      this.ARows.push(this.ACells[x]);

Solution

  • When you call document.getElementById TypeScript doesn't know what is the specific type of the element, so the function returns the generic type HTMLElement. You should cast it to HTMLTableElement.

    Try something like this:

    var table = document.getElementById("CompareParts") as HTMLTableElement;