2017-08-29 83 views
0

我在使用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

放置在layout.component.html @Carsten – tolceza

+0

你找到了解決方案嗎?我有同樣的問題@tolceza – natdico

回答

0

這應該給您滾動事件:

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

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

謝謝,但它甚至沒有檢測到滾動事件。 – tolceza

0

您的佈局必須是問題的根源。滾動事件僅在組件模板元素可以實際滾動時起作用。 看到我製作的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

相關問題