在Angular4中,当滚动事件(`onScroll`)被触发时,会执行相应的函数。

17

我正试图显示一个分页列表,因此,当用户向下滚动时,我想触发一个函数来加载更多的项目。但我无法在“滚动”事件上调用该函数。

这是我的HTML文档的样子:

   <div id="notifications-list"  (scroll)="scrollHandler($event)"  >
       <div class="row notification-row" *ngFor = "let notification of notifications" > 
                ...
       </div>
    </div>

在我的 .ts 文件中,我有以下内容:

      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');
  }

但这种方式行不通。我的控制台中没有显示任何内容。 我尝试了许多其他方式,比如使用@HostListener,但它也不起作用:

@HostListener('window:scroll', ['$event']) 
    dotheJob(event) {
      console.debug("Scroll Event", window.pageYOffset );
    }

你能帮我解决这个问题吗?谢谢!:)


1
只有在滚动整个页面时才起作用,如果想要监听元素滚动的事件,则需要监听该元素的“scroll”事件。请提供更多信息(例如Plunker)以获取更详细的信息。 - Günter Zöchbauer
1个回答

22

使用@HostListener时,您提供了一个不同的函数名称。请按照以下方式修改您的代码:

@HostListener('window:scroll', ['$event']) 
    scrollHandler(event) {
      console.debug("Scroll Event");
    }

并且模板

<div id="notifications-list"  (scroll)="scrollHandler($event)"  >
       <div class="row notification-row" *ngFor = "let notification of notifications" > 
                ...
       </div>
    </div>

请在这里查看plunk希望有所帮助。

上面的代码将在页面滚动和div滚动时触发scroll函数。如果您只想使用div滚动事件,请使用以下代码

@HostListener('scroll', ['$event']) 
        scrollHandler(event) {
          console.debug("Scroll Event");
        }

只有当滚动到该div时,此内容才会被触发。在这里找到plunkhere


是的,这个方法可行,但只有当我滚动整个页面时才适用。我想要的是仅在我滚动到特定的 div 上时触发此函数:<div id="notifications-list" (scroll)="scrollHandler($event)" >。我该如何实现呢? - Emanuela Colta
1
似乎对于div也能正常工作..https://plnkr.co/edit/5AnODiyWhqVHYn10a7qT?p=preview - Vikhyath Maiya
是的,它可以工作。我需要添加一个高度并设置 overflow-y:scroll。谢谢! - Emanuela Colta
谢谢你! - Carlo Nyte

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接