I am trying to display a paginated list, terefore, when the user scrolls down, I want to trigger a function that loads more items. But I cannot call the function on 'scroll' event.
This is how my HTML doc looks like:
<div id="notifications-list" (scroll)="scrollHandler($event)" >
<div class="row notification-row" *ngFor = "let notification of notifications" >
...
</div>
</div>
And in my .ts file, I have the following:
import { Component, OnInit, ViewChild, ViewEncapsulation, AfterViewChecked, ElementRef, HostListener } from '@angular/core';
@Component({
selector: 'header-component',
templateUrl: 'header.component.html',
styleUrls: ['header.component.css'],
encapsulation: ViewEncapsulation.None,
})
export class HeaderComponent implements OnInit {
constructor( ...){}
scrollHandler(event){
console.log(event);
console.log('now you are scrolling');
}
But it won't work this way. Nothing is displayed in my console.
I tried in many other ways, such as using the @HostListener
, but it did't work:
@HostListener('window:scroll', ['$event'])
dotheJob(event) {
console.debug("Scroll Event", window.pageYOffset );
}
Can you help me with this issue? Thank you! :)
Perhaps the easiest method of listening to the scroll events: bind to the actual HTML element. Even easier, you can window scroll from any HTML element in the DOM, using the window:scroll event emitter.
Definition and Usage. The onscroll event occurs when an element's scrollbar is being scrolled. Tip: use the CSS overflow style property to create a scrollbar for an element.
Use the @HostListener decorator to listen for the window:scroll event. Use scrollHeight instead of offsetHeight or clientHeight if the content to hook the event to scrollable.
You have given a different function name while using @HostListner.Modify your code as
@HostListener('window:scroll', ['$event'])
scrollHandler(event) {
console.debug("Scroll Event");
}
and template
<div id="notifications-list" (scroll)="scrollHandler($event)" >
<div class="row notification-row" *ngFor = "let notification of notifications" >
...
</div>
</div>
Please check the plunk here.Hope it helps.
The above code will trigger scroll function both when the page is scrolled as well as the div is scrolled .If you want only div scroll event,please use the following code
@HostListener('scroll', ['$event'])
scrollHandler(event) {
console.debug("Scroll Event");
}
This will be triggered only that div is scrolled.Find the plunk here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With