Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 313
DevStacker Avatar asked Dec 02 '19 23:12

DevStacker


2 Answers

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!

like image 181
Amineze Avatar answered Sep 20 '22 13:09

Amineze


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.

like image 44
Bullsized Avatar answered Sep 21 '22 13:09

Bullsized