2

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

Sufiyan Khan
  • 23
  • 1
  • 4
  • 1
    what you have done so far? feel free to share your code so we will get batter idea what went wrong. – Yash Rami Jul 02 '19 at 12:48
  • @ViewChild('lTable') lTable; the reference to the table from the template. i have the index of the row and column of the td that i intend to target .I just want to know can i access the td with the lTable object in my component – Sufiyan Khan Jul 02 '19 at 12:49
  • try like this ` @ViewChild('ITable') ITableRef: ElementRef;` and on some event `this.ITableRef.nativeElement.focus();` – Yash Rami Jul 02 '19 at 12:51
  • by this i am getting the table object my motive is to target a particular column by its index – Sufiyan Khan Jul 02 '19 at 12:55
  • @SufiyanKhan, take a look to https://stackoverflow.com/questions/56562871/angular-6-html-table-create-dynamic-columns-and-rows. See that in comments there are an example using simple tables in https://stackblitz.com/edit/angular-wmfjhh-vkeegy?file=app%2Ftable-basic-example.ts (in a mat-table the the order of the viewchildren in a mat-table goes from top to down and to left to rigth) – Eliseo Jul 02 '19 at 16:52

2 Answers2

1

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)

Nithya Rajan
  • 4,722
  • 19
  • 30
0

To Focus on first input field of table =>

focusTD(rowNum, cellNum) this.ITableRef.nativeElement.tBodies[0].rows[rowNum].cells[cellNum].getElementsByTagName('input')[0].focus() }

  • Welcome to SO. Please note, that the question was about accessing arbitrary table fiends, not necessarily the first input field. Additionally, you can make use of our formatting possibilities to make your code more readable. – ahuemmer Dec 20 '22 at 08:16