Daniel Stephens
Daniel Stephens

Reputation: 3249

scrollIntoView does not trigger mousewheel nor scroll event in Angular

I use Angular and registered a mousewheel and scroll event. When I use scrollIntoView this event is not triggered. Is there any other event I miss?

  @HostListener('mousewheel', ['$event'])
  mousewheel(event: MouseEvent) {
    console.log("mousewheel");
  }

  @HostListener('scroll', ['$event'])
  scroll(event: MouseEvent) {
    console.log("scroll");
  }

And I use the function as this:

element.scrollIntoView({behavior: 'smooth'});

Does anyone know what I miss here?

Upvotes: 0

Views: 1379

Answers (1)

HenryDev
HenryDev

Reputation: 4993

You can always use addEventListener to add the scroll functionality. Also, don't forget to remove it in ngOnDestroy Here's an example:

export class WindowScrollDirective implements OnInit, OnDestroy{

 ngOnInit() {
    window.addEventListener('scroll', this.handleScroll, true); 
 }

 ngOnDestroy() {
     window.removeEventListener('scroll', this.handleScroll, true);
 }

 handleScroll = (event): void => {
   //handle your scroll here
   
 };
}

NOTE: you can replace the window object by the element you want to use for scrolling.

Upvotes: 1

Related Questions