I am working with a table that has three columns. The first column contains text, while the second and third columns have input fields. I can navigate within a row using keyCode
to move to the right, but once I reach the last column, I am unable to jump to the next row. What changes do I need to make in my code to enable this functionality?
To see the code in action, visit my StackBlitz: https://stackblitz.com/edit/angular-wmfjhh-vhkikf?file=app%2Ftable-basic-example.ts
Here is a snippet of the code:
// Snippet from HTML
<tbody formArrayName="rows" *ngIf="rows && rows !== null && !isLoading">
<tr class="optimize-row" *ngFor="let rowControl of rows.controls; let rowIndex = index">
<td [formGroupName]="rowIndex" *ngFor="let column of displayedColumns; let columnIndex = index;">
<div *ngIf="attributesWithFormControls.includes(column.attribute); else otherColumns">
<span>
<label>
<input style="background-color: silver" [id]="'row-' + rowIndex + '-col-' + columnIndex" type="text" arrow-div [formControl]="rowControl.get(column.attribute)" (focus)="onFocus($event)">
</label>
</span>
</div>
<ng-template #otherColumns>
<div tabindex="0" [id]="'row-' + rowIndex + '-col-' + columnIndex" arrow-div>
Here is a Number
</div>
</ng-template>
</td>
</tr>
</tbody>
// TS
/**
* Use arrowKey
* @param object any
*/
move(object) {
console.log('move', object);
const id = object.element.nativeElement.id;
console.log(id);
const arr = id.split('-');
let row: number = Number(arr[1]);
let col: number = Number(arr[3]);
switch (object.action) {
case 'UP':
--row;
break;
case 'DOWN':
++row;
break;
case 'LEFT':
--col;
break;
case 'RIGTH':
++col;
break;
}
this.setFocus(row, col);
}
onFocus(event: FocusEvent): void {
console.log('onFocus', event.target);
const target = event.target as HTMLElement;
if (target.tagName === 'INPUT') {
this.currentInputInFocus = target;
}
}
private setFocus(row: number, col: number) {
console.log(`setFocus [row:${row}] [col:${col}]`);
const newElementToFocusOn = document.getElementById(
`row-${row}-col-${col}`
);
if (newElementToFocusOn) {
console.log('focusing');
this.currentInputInFocus = newElementToFocusOn;
this.currentInputInFocus.focus();
}
}