在Hostlistener上滚动事件

时间:2016-08-03 16:03:02

标签: angular

我已经定义了模板

@Component({
    selector: 'name',
    directives: [ ... ],
    templateUrl: 'name.html'
})

和班级

export class ProductGridComponent implements OnInit {
    @HostListener('scroll', ['$event'])
    onScroll(e) {
        alert(window.pageYOffset)
    }

    products = [];
}

但它没有拍摄任何东西,但是当我用click和onClick替换scroll和onScroll时它确实会显示警告。

为什么它不能用于滚动,angular2是否有任何其他实现呢?

由于

6 个答案:

答案 0 :(得分:7)

假设您要显示主机滚动(而不是一个窗口)并且您正在使用角度+2.1

  @HostListener('scroll', ['$event']) private onScroll($event:Event):void {
    console.log($event.srcElement.scrollLeft, $event.srcElement.scrollTop);
  };

答案 1 :(得分:7)

您可以创建像bellow

这样的自定义指令
import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[scroller]'
})
export class ScrollerDirective {

  @HostListener('scroll') scrolling(){
    console.log('scrolling');
  }

  @HostListener('click') clicking(){
    console.log('clicking...');
  }

  constructor() { }

}

然后假设你有一个像

这样的html模板
<div class="full-width" scroller>
    <div class="double-width"></div>
</div>

使用以下css

.full-width{
    width: 200px;
    height: 200px;
    overflow: auto;
}

.double-width{
    width:400px;
    height: 100%;
}

控制台将打印&#34;滚动&#34;如果移动水平滚动条,则运行应用程序。

这里的关键是 - scoller指令应该在父级而不是子级div中。

答案 2 :(得分:3)

在模板中的相应元素处设置<?php if (isset($_POST["XML"])) { //put .xml file into server directory ./XML Files echo "success"; } else echo "error"; ?>

答案 3 :(得分:2)

您也可以通过以下代码进行操作:

Function

答案 4 :(得分:1)

@HostListener('document:wheel', ['$event.target'])
public onWheel(targetElement) {
    console.log()
}

答案 5 :(得分:1)

在 angular 10 及更高版本中,在监听窗口事件时执行以下操作:

import { HostListener } from '@angular/core';

@HostListener('window:scroll', ['$event']) onScroll($event: Event): void {
    if($event) {
      console.log($event));
    }
  }
相关问题