Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix header after scrolling Angular 4

I am having issue fixing the header after scrolling, I tried a lot of stuff but can't get it to work. I checked this thread but it doesnt work for me: Angular 4 @HostListener Window scroll event strangely does not work in Firefox . This is my component structure:

  • Layout
    • Steps
  • Routes

Inside steps is my header which I want to fix, after scrolling for 50px. Inside Layout is some other content like a div with logo background (above the content of steps).

This is what I tried inside Steps.ts

@HostListener('window:scroll', [])
  onWindowScroll() {
    const number = window.scrollY;
    if (number > 40) {
      this.fixed = true;
    } else if (this.fixed && number < 10) {
      this.fixed = false;
    }
  }

but the problem is that scroll is not triggering at all. I found examples where scroll logs the event, but for me it doesn't work (I tried with $event as well). Anyone has a solution?

like image 440
Nemanja Grabovac Avatar asked Aug 30 '17 09:08

Nemanja Grabovac


2 Answers

Found a solution. On my layout component I put a function

(scroll)="onWindowScroll($event)"

and in layout component i used:

@HostListener('window:scroll', ['$event'])
  onWindowScroll($event) {
    const number = $event.target.scrollTop;
    if (number > 40) {
      this.fixed = true;
    } else if (this.fixed && number < 10) {
      this.fixed = false;
    }
  }

I removed Steps component since I didnt need it anymore, all the content is inside layout now.

like image 145
Nemanja Grabovac Avatar answered Oct 21 '22 16:10

Nemanja Grabovac


In Angular 5+ it works a little differently:

const number = $event.target.scrollingElement.scrollTop || $event.target.documentElement.scrollTop;
like image 20
Adrian Avatar answered Oct 21 '22 16:10

Adrian