Angular 8 @HostListener('window:scroll', []) not working

我怕爱的太早我们不能终老 提交于 2021-01-26 17:59:39

问题


I have attempted to use HostListener to track the scroll position to change colour of the my header.

My header component is as follows,

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

constructor(@Inject(DOCUMENT) private document: Document) { }

  ngOnInit() {
  }

  @HostListener('window:scroll', [])
  onWindowScroll() {
    console.log(window.scrollY);
  }

}

but when I am scrolling I am not getting any logs in console.

I have trying putting the HostListener in the main app.component, as my header component is positing fixed, However I am still getting no results, and no errors.

Thanks


回答1:


This is because of the global styles from styles.scss

From styles.scss change height to min-height

html, body {
    height: 100%;
}

To this

html, body {
    min-height: 100%;
}

This is what worked for me, hope it help!




回答2:


In your .ts file for the component that you are working on:

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

...
constructor(
    @Inject(DOCUMENT) private document: Document
)
... after ngOnIt {}:
@HostListener('window:scroll', [])
onWindowScroll() {
    console.log(window.scrollY);
}

Make sure that the file is long enough and you should see integers in the console when you scroll down the viewport.



来源:https://stackoverflow.com/questions/59148204/angular-8-hostlistenerwindowscroll-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!