简体   繁体   中英

How to handle events of scroll top\bottom on Angular?

I have a div with virtual scroll items. I want to get events when i scroll on top and when i scroll to bottom.

html:

<div class="col-lg-6 " #scroll id="scrollable" (scroll)="onScroll($event)" du-smooth-scroll>
      <cdk-virtual-scroll-viewport itemSize="14" style="height: 520px; width: 85%;" >
        <li *cdkVirtualFor="let n of lines" class="lazyLogLine">
          {{n}}
        </li>
      </cdk-virtual-scroll-viewport>
</div>

*.ts:

 onScroll = (event): void => {
//handle your scroll here
//this is used to be able to remove the event listener
this.scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
console.log('scrolling ' + this.scrollTop);
if (this.scrollTop > 5) {
  this.showPreviosLog(this.previosLink);
  console.log('scroll top');
}
else {
  console.log('scroll bottom');
} 

But, i think it is not valid solution.

i know, that Angular have ScrollDispatcher . Can i use this dispatcher to handle scroll up and bottom? If so, how?

Thank you!

You can try these 2 approach

@ViewChild("scroll", { static: true }) scrollEle: ElementRef;

fromEvent(scrollEle, "scroll")
    .pipe(
        tap()// do something here
    )
    .subscribe();

or

@HostListener("window:scroll", ["$event"])
onScroll(event) {
       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM