Angular 7滚动事件不启动



用于在MatDialog组件中的Angular应用程序中实现间谍导航栏。我实现了一个指令,使用监视滚动事件

@HostListener('window:scroll', ['$event'])

我还尝试将'scroll'作为事件名称。但这场活动似乎并没有引起轰动。我尝试了几种方法,例如,直接在对话框组件中使用HostListener,使用JavaScriptwindow.onscroll()函数和rxjsfromEvent()函数,但都没有成功。

尝试其他css事件(例如window:click(可以正常工作。我还在一个不显示为对话框的"正常"组件中尝试了它,但事件也没有在那里触发。

造成这种行为的原因是什么?

这里有一个运行良好的替代解决方案。

简而言之:

ngOnInit() {
// Add an event listener to window
// Window can be defined in the pollyfiles.ts as: 
// if (window) {
//    (window as any).global = window;
// }
window.addEventListener('scroll', this.scroll, true); //third parameter
}
ngOnDestroy() {
window.removeEventListener('scroll', this.scroll, true);
}
scroll = (event: any): void => {
// Here scroll is a variable holding the anonymous function 
// this allows scroll to be assigned to the event during onInit
// and removed onDestroy
// To see what changed:
const number = event.srcElement.scrollTop;
console.log(event);
console.log('I am scrolling ' + number);
};

这种行为的原因是有角度的材质阻挡了滚动事件。

我是这样解决的:

ngAfterViewInit(): void {
const content = document.querySelector('.mat-dialog-container');
const scroll$ = fromEvent(content, 'scroll').pipe(map(() => content));
scroll$.subscribe(element => {
// do whatever
});
}

试试这个。。。不需要使用html做任何事情。

import { Component, OnInit, HostListener } from '@angular/core';
@HostListener('window:scroll', ['$event']) getScrollHeight(event) {
console.log(window.pageYOffset, event);
}

最新更新