'Angular: How can I prevent the scrollbar from moving when navigating with the arrow keys up and down?
I have developed a table and which I have integrated a self-created navigation. Problem is, when I scroll up and down so always moves the scrollbar with. Is there a way when I press keydown or keyup that the scrollbar does not move. I know that it is hostListener feasible. But I have not found out how to implement it. Can you help me please?
My Code:
// DIRECTIVE
constructor(private keyboardService: KeyboardService,
public element: ElementRef,
private render: Renderer2) {
this.render.setAttribute(this.element.nativeElement, 'tabindex', '0');
}
@HostListener('keydown', ['$event']) onKeyUp(e) {
switch (e.keyCode) {
case 38:
this.keyboardService.sendMessage({ element: this.element, action: 'UP' });
break;
case 37:
this.keyboardService.sendMessage({ element: this.element, action: 'LEFT' });
break;
case 40:
this.keyboardService.sendMessage({ element: this.element, action: 'DOWN' });
break;
case 39:
this.keyboardService.sendMessage({ element: this.element, action: 'RIGTH' });
break;
}
}
// Component
/**
* Use arrowKeys
* @param object any
*/
move(object) {
const inputToArray = this.inputs.toArray();
let index = inputToArray.findIndex((x) => x.element === object.element);
switch (object.action) {
case 'UP':
index -= this.columns.length;
break;
case 'DOWN':
index += this.columns.length;
break;
case 'LEFT':
index--;
break;
case 'RIGTH':
index++;
break;
}
if (index >= 0 && index < this.inputs.length) {
inputToArray[index].element.nativeElement.focus();
}
}
My StackBlitz: https://stackblitz.com/edit/stackoverflow-72056135-buytsq?file=app%2Ftable-basic-example.html
Solution 1:[1]
When I get here, I want the scrollbar to move first:
If the scrollbar moves after each keydown, cells with focus at the top are no longer visible properly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | oregairu2022 |


