Reputation: 278
I'm trying to hide a div when user scroll the page, and when stop scroll I want to show the div.
I'm using @HostListener but it fired only user scroll the page.
@HostListener('window:scroll', ['$event'])
onScroll(event) {
this.scroll = true;
setTimeout(() => {
this.scroll = false;
}, 2000);
}
Upvotes: 3
Views: 4721
Reputation: 1698
You can use RxJs's debouncetime for this usecase.
fromEvent(window, "scroll").pipe(
tap(() => this.scroll = true),
debounceTime(100)
).subscribe(() => {
this.scroll = false;
});
Stackblitz example: https://stackblitz.com/edit/angular-dumymv
Upvotes: 4
Reputation: 73761
To improve your current code, call clearTimeout
when the scroll
event is detected. It will prevent the div from showing up until you stop scrolling for the specified amount of time.
public scroll = false;
private timeout: number;
@HostListener('window:scroll', ['$event'])
onScroll(event) {
this.scroll = true;
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this.scroll = false;
}, 300);
}
See this stackblitz for a demo.
Upvotes: 7
Reputation: 2342
Your approach works. And this Stackblitz proves it: https://stackblitz.com/edit/angular-5xcm6h
You may have an error somewhere else.
Upvotes: 0