typescript 如何使 HostListener 滚动工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41319227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make HostListener for scroll work?
提问by Baruch
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
. I've searched for similar questions in SO but even though my code is essentially the same it still doesn't work.
两者都不会触发console log
. 我在 SO 中搜索了类似的问题,但即使我的代码基本相同,它仍然不起作用。
回答by yurzui
Using host inside component decorator
在组件装饰器中使用主机
it should be:
它应该是:
'(window:scroll)' : 'onWindowScroll($event)'
Using HostListener inside component decoratorYour syntax looks correct
在组件装饰器中使用 HostListener您的语法看起来正确
@HostListener('window:scroll', ['$event'])
public onWindowScroll(event: Event): void {
console.log('scrolled');
}
You can also make sure that your component has scroll. In my examples i imitate scroll via:
您还可以确保您的组件具有滚动功能。在我的例子中,我通过以下方式模仿滚动:
styles: [`
:host {
display: block;
height: 2000px;
}
`]
回答by ray whatley
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
});
}`
回答by Vega
(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 高度,但它不喜欢那样。