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
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With