0
@HostListener('window:scroll', ['$event'])
public handleScroll(event: any): void {
 
}

This is working with window scroll, but, sometimes, the scroll bar is appearing on other element. so, I want to watch all events.

So, I want to like below function, but, below will make error.

@HostListener('*:scroll', ['$event'])

1 Answer 1

1

You can add a document-level scroll event listener with useCapture parameter of true to capture the scroll events on all elements. (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)

Unfortunately, it's still not possible to do this with HostListener in Angular. You have to register and unregister you handler using addEventListener.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  scroll = (e) => console.log(`scrolled: ${e.target.id}`);

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

  ngOnDestroy() {
    document.removeEventListener('scroll', this.scroll);
  }
}

https://stackblitz.com/edit/angular-ivy-ohsjwd?file=src/app/app.component.ts

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, I will check soone
This helps me, and, I used this code for my project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.