Search code examples
htmlangularangular6

Angular set focus to an input that is in a <td> of the table Using table object in component


I have a table which populates data dynamically.I have multiple input tags in it and I want to shift the focus for the input to the next input which is in the next td tag when a user press the right arrow key (similar to ms excel)

I have the index of row and column and have create a object of table using @ViewChild but i am unable to pin point the targeted td using the index of the row and the column


Solution

  • You can access the particular cell (td) using the table ElementRef which you already have.

    @ViewChild('ITable') ITableRef: ElementRef;
    
    focusTD(rowNum, cellNum)
       this.ITableRef.tBodies[0].rows[rowNum].cells[cellNum].focus()
    }
    
    ngAfterViewInit() {
      this.focusTD(0,1); // selects the first tr (row) and second td (cell)
    }
    

    Table element has tBodies, I selected the first tBodies assuming your table has a single tBody, then you should select a row (tr) and then you can select the particular cell (td)