Google brought up an interesting point that the approved answer addresses the question but lacks guidance on finding a solution.
I expanded upon Alex's response because I needed a way to utilize the functionality already present in my @HostListener
for fetching notifications based on different screen sizes.
For instance, in my application, the notifications page has its own route on mobile devices but is located in the sidebar on tablets and larger screens. Therefore, using the @HostListener
there wouldn't work as it would only activate when reaching the bottom of the entire page, not the sidebar specifically.
Instead, I targeted the specific <div>
I was interested in and attached the necessary functionalities. Here is the code snippet:
attachListenerToContainer() {
let elementToListenTo = this.ele ? this.ele : 'window';
this.renderer.listen(elementToListenTo, 'scroll', (event) => {
if(!this.reachedBottom) {
if((getHeight(this.ele) + getScrollTop(this.ele)) >= getOffset(this.ele)) {
this.reachedBottom = true;
this.getNextNotificationsPage();
}
}
});
function getScrollTop(ele) {
return ele ? ele.scrollTop : window.scrollY;
}
function getHeight(ele) {
return ele ? ele.clientHeight : window.innerHeight;
}
function getOffset(ele) {
return ele ? ele.scrollHeight : document.body.offsetHeight;
}
}
The this.ele
references the container div I'm interested in, which I locate within the ngAfterViewInit()
lifecycle hook for tablet-sized screens and above. If the element cannot be found, I default to using the window, effectively mimicking the behavior of @HostListener
.
Additionally, here's how I located the desired container element in my case:
this.ele = document.getElementsByClassName('notifications')[0];