I have written a table and in it all contain input fields. For this template I have developed a keyCode navigation. A navigation up, down, left and right is possible. What do I have to add to my code so that the cursor is focused directly in the when navigating?
My Code:
// Snippet from HTML
...
<tbody formArrayName="rows">
<tr *ngFor="let rowControl of rows.controls; let rowIndex = index">
<td [formGroupName]="rowIndex" appArrowKeyNav *ngFor="let column of displayedColumns; let columnIndex = index;">
<div>
<span>
<label>
<input [formControl]="rowControl.get(column.attribute)">
</label>
</span>
</div>
</td>
</tr>
</tbody>
// TS
public move(object: any) {
const inputToArray = this.inputs.toArray();
const cols = this.displayedColumns.length;
let index = inputToArray.findIndex((x) => x.element === object.element);
// console.log('Index found:', index);
switch (object.action) {
case 'UP':
index -= cols;
break;
case 'DOWN':
index += cols;
break;
case 'LEFT':
index -= 1;
break;
case 'RIGHT':
index += 1;
break;
}
if (index >= 0 && index < this.inputs.length) {
console.log('Navigating to index:', index);
inputToArray[index].element.nativeElement.focus();
}
}
// Directive
@HostListener('keydown', ['$event']) onKeyUp(event: KeyboardEvent) {
switch (event.key) {
case 'ArrowUp':
this.keyboardService.sendMessage({ element: this.element, action: 'UP' });
break;
case 'ArrowLeft':
this.keyboardService.sendMessage({ element: this.element, action: 'LEFT' });
break;
case 'ArrowDown':
this.keyboardService.sendMessage({ element: this.element, action: 'DOWN' });
break;
case 'ArrowRight':
this.keyboardService.sendMessage({ element: this.element, action: 'RIGHT' });
break;
case 'Enter':
this.keyboardService.sendMessage({ element: this.element, action: 'ENTER' });
break;
}
}
Here is myStackblitz: https://stackblitz.com/edit/angular-wmfjhh-zfkyyx?file=app%2Ftable-basic-example.html