onScroll事件触发Angular4中的函数

Ema*_*lta 8 html event-handling onscroll typescript angular

我试图显示一个分页列表,因为当用户向下滚动时,我想触发一个加载更多项目的函数.但我不能在'scroll'事件上调用该函数.

这就是我的HTML文档的样子:

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

在我的.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');
  }
Run Code Online (Sandbox Code Playgroud)

但它不会这样.我的控制台中没有显示任何内容.我尝试过许多其他方式,比如使用@HostListener,但它不起作用:

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

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

Vik*_*iya 12

使用@ HostListner时,您已经给出了不同的函数名称.将您的代码修改为

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

和模板

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

请检查这里的插件.希望它有所帮助.

上面的代码将在页面滚动以及div滚动时触发滚动功能.如果您只想要div滚动事件,请使用以下代码

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

仅在滚动div时才会触发此操作.在此处查找插件