Reputation: 5566
I have a Facebook-like app, where feeds are populated. I have a scroll on my <body>
but these feeds are in some nested child component <app-feeds>
. I want to implement an infinite scroll without using any library like ngx-infinite-scroll
or so....
To implement that I'm using @HostListener()
on the complete document. But console.log('End') is not getting fired when document scroll is reached at the end. Below is my implementation... Somebody, please help me with this.
@ViewChild('feedSection') el: ElementRef;
@HostListener('document:scroll', ['$event'])
onScroll(event: any) {
const elm = this.el.nativeElement;
if (elm.offsetHeight + elm.scrollTop >= elm.scrollHeight) {
console.log('End');
}
}
My app-feed
component is
<app-home>
<div #feedSection class="feed-container">
...
</div>
</app-home>
Upvotes: 1
Views: 165
Reputation: 5566
So I got the answer to this question. to solve it without any library of course. the element itself scrolls and not the whole window. In this case, as the whole window is the scroll I need another approach:
@HostListener('document:scroll', ['$event'])
onScroll(event: any) {
const boundingBox = document.documentElement.getBoundingClientRect();
if (boundingBox.height - window.scrollY === window.innerHeight) {
console.log('End');
}
}
PS - One guy (@alpox) on Gitter suggested me this approach and it works just fine. So I'm posting it here in case anyone else is looking for similar functionality in Angular.
Upvotes: 1
Reputation: 9764
You need to find the values for 'offsetHeight', 'scrollHeight' properties using console.log(). In one of my previous project I subtracted offset value of '20px' in order to execute the scroll end condition. It may vary between browsers.
Upvotes: 1