Angular4 中 onScroll 事件触发函数

2023-12-21

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

我的 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 );
    }

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


您在使用 @HostListner 时给出了不同的函数名称。将代码修改为

@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>

请检查一下here https://plnkr.co/edit/MGsiQnqkRe87jCDqIEVV?p=preview。希望能帮助到你。

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

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

仅当 div 滚动时才会触发。找到 plunkhere https://plnkr.co/edit/m4JswZ4q63VNb0yZpo7W?p=preview

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular4 中 onScroll 事件触发函数 的相关文章