1

I'm working with Angular 7, and I have a directive that listens to the scrolling of an element. The problem is, that I want the directive to respond only to manual scrolls, and ignore programmatic scrolls done with element.scrollTop = x. The directive contains a scroll listener, like so:

@HostListener('scroll', ['$event'])
  onScroll($event) {
  }

In one of the places in my code I set a programmatic scrollTop as described above, and an event was caught by the listener. I tried to find a property on $event that would indicate whether the event was manual or not, but couldn't find one. Did I miss it? Or perhaps that I can somehow trigger a custom event in vanilla javascript that would contain such indication (I know that in jQuery you can do that, but I'm not using jQuery here...). Thanks.

1
  • 1
    Since you are the one performing the programmatic scroll, you could set a variable in that point or you could add a getter for the scrollTop property Commented Feb 27, 2019 at 15:43

1 Answer 1

2

Just add a flag and set it to false before you manual scroll.

Don't forget to set the flag back to true in your scroll handler

private handleScroll = true;

@HostListener('scroll', ['$event'])
onScroll($event) {
  if (!this.handleScroll) {
    this.handleScroll = true;
    return;
  }
}

public manualScroller() {
  this.handleScroll = false;

  this.element.scrollTop = 100;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Did you check my answer at all? manualScroller method will set a flag to false so scroll handler will check if that flag is false it will return
@messerbill, OG has posted only his scroll handler. Why do you think I should know who and when should call manualScroller? It is a method to manually scroll the content and set a flag so onScroll method will check if it is a manual scroll or from code. Your downvote and comment makes no sense therefore feel free to create more accounts to downvote
Well, your response does not answer the question that OP asked at all. He is asking how to detect if the scroll was manual or programmatic (done from .ts).

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.