angularinputscrollangular-materialtooltip

Angular Material: Number Input Scrolling Behavior Changes After Hovering Over MatTooltip


I'm working with Angular 11 and Angular Material. I've encountered an unexpected behavior change in a <input matInput type='number'> with matInput. Normally, when I scroll over this input field, the page scrolls. However, if I hover over any element with MatTooltip and then focus back on the number input field, scrolling behavior changes: instead of scrolling the page, it increments or decrements the number in the input. This issue also occurs on the Angular Material official website.

I expected the number input field to maintain consistent scrolling behavior, irrespective of interacting with MatTooltip. To resolve this, I tried various approaches to prevent the number from changing and maintain page scrolling. My goal was to ensure that scrolling over a focused number input field always results in page scrolling, not in changing the input value.


Solution

  • I resolved the issue using a custom Angular directive that overrides the default scrolling behavior of a number input field. This directive listens for the mouse wheel event and, instead of allowing the number to change, it scrolls the page. Here’s how it's implemented and used:

    import { Directive, HostListener } from '@angular/core';
    
    @Directive({
      selector: '[scrollOverride]' 
    })
    export class ScrollOverrideDirective {
    
      @HostListener('wheel', ['$event'])
      onWheel(event: WheelEvent): void {
        event.preventDefault();
        window.scrollBy(0, event.deltaY);  // Manually handle the scrolling of the page
      }
    }
    

    This directive listens for the 'wheel' event on the elements it's applied to. When the event is triggered, it prevents the default behavior of the number input and manually scrolls the page.

    With this directive, scrolling over a number input field affected by MatTooltip will now result in the page scrolling, rather than changing the input value.