使用@HostListener不工作的窗口滚动事件

问题描述:

我在使用Angular 4应用程序向下滚动时遇到粘贴头问题。无法检测到滚动事件。使用@HostListener不工作的窗口滚动事件

标题放置在布局组件中,我想要滚动的内容放置在路由组件中。这可能是问题吗?

这是我实施的代码。

在layout.component.ts

import { Component, OnInit, HostListener, Inject } from '@angular/core'; 

import { DOCUMENT } from "@angular/platform-browser"; 

@Component({ 

    selector: 'app-layout', 

    templateUrl: './layout.component.html', 

    styleUrls: ['./layout.component.css'] 
}) 

export class LayoutComponent implements OnInit { 

    public navIsFixed: boolean = false; 

    constructor(public router: Router, @Inject(DOCUMENT) private document: any) { } 

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

    onWindowScroll(){ 
     const number = window.pageYOffset || 
     document.documentElement.scrollTop || 
     document.body.scrollTop || 0; 
     if (number > 50) { 
     this.navIsFixed = true; 
     } else if (this.navIsFixed && number < 10) { 
     this.navIsFixed = false; 
     } 
    } 
} 

在layout.component.html

<div [class.fixed]="navIsFixed" class="header"> 
+0

如果你在顶级组件定义的呢? app.component.ts(我假设你的路由器出口在那里......) – Carsten

+0

router-outlet>放置在layout.component.html @Carsten – tolceza

+0

你找到了解决方案吗?我有同样的问题@tolceza – natdico

这应该给您滚动事件:

@HostListener('scroll', ['$event']) 
onScroll(event) { 
    ... 
} 

<div (scroll)="onScroll($event)" 
+0

谢谢,但它甚至没有检测到滚动事件。 – tolceza

您的布局必须是问题的根源。滚动事件仅在组件模板元素可以实际滚动时起作用。 看到我制作的stackblitz。更改div尺寸,滚动不会被触发。 为了使它工作,我会建议使其符合指令,并设置为一个具有100vh高度和100vw宽度的div。

从'@ angular/core'导入{Directive,ElementRef,HostListener};

@Directive({ selector: '[trackScroll]' }) 
export class TrackScrollDirective { 
    constructor(private el: ElementRef) { 
    } 

    @HostListener('document:scroll', []) 
    onScroll(): void { 
     console.log('I am scrolled'); 
    } 
} 

stackblitz

+0

请参阅最新演示 – Vega