简体   繁体   English

如何使 HostListener 滚动工作?

[英]How to make HostListener for scroll work?

I'm trying to add a window:scroll listener but when scrolling nothing happens我正在尝试添加一个window:scroll侦听器但是滚动时什么也没有发生

What I've tried so far:到目前为止我尝试过的:

using host inside component decorator在组件装饰器中使用host

@Component({
  ...
  host: {
    'window:scroll' : 'onWindowScroll($event)'
  },
  ...
)
export class PageWrapperComponent implements OnInit {
  ...
  public onWindowScroll(event: Event): void {
    console.log('scrolled');
  }
  ...
}

using HostListener inside component decorator在组件装饰器中使用HostListener

export class PageWrapperComponent implements OnInit {
  ...
  @HostListener('window:scroll', ['$event'])
  public onWindowScroll(event: Event): void {
    console.log('scrolled');
  }
  ...
}

I also tried using it in an attribute directive but it didn't work either我也尝试在属性指令中使用它,但它也不起作用

Neither will trigger the console log .两者都不会触发console log I've searched for similar questions in SO but even though my code is essentially the same it still doesn't work.我在 SO 中搜索了类似的问题,但即使我的代码基本相同,它仍然不起作用。

Using host inside component decorator在组件装饰器中使用主机

it should be:它应该是:

'(window:scroll)' : 'onWindowScroll($event)'

Plunker Example Plunker 示例

Using HostListener inside component decorator Your syntax looks correct在组件装饰器中使用 HostListener您的语法看起来正确

@HostListener('window:scroll', ['$event'])
public onWindowScroll(event: Event): void {
  console.log('scrolled');
}

Plunker ExamplePlunker 示例

You can also make sure that your component has scroll.您还可以确保您的组件具有滚动功能。 In my examples i imitate scroll via:在我的例子中,我通过以下方式模仿滚动:

styles: [`
    :host {
      display: block;
      height: 2000px;
    }
`]

My team and I recently ran into this issue.我和我的团队最近遇到了这个问题。 Our solution was to use angular's Renderer to set a listener for the 'scroll' event on the elementRefs parentNode.我们的解决方案是使用 angular 的 Renderer 为 elementRefs parentNode 上的 'scroll' 事件设置一个监听器。

`constructor(
  private _renderer: Renderer,
  private _elementRef: ElementRef
) {
  this._renderer.listen(this._elementRef.nativeElement.parentNode, 
   'scroll', (event) => {
      // do stuff with the event
  });
}`

(Posted on behalf of the question author) . (代表问题作者发表)

I was able to out why HostListener wasn't working, I am using angular/material component library and I overrode the md-sidenav-layout height with 100vh and it didn't like that.我能够找出 HostListener 不工作的原因,我使用的是 angular/material 组件库,我用 100vh 覆盖了 md-sidenav-layout 高度,但它不喜欢那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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