简体   繁体   中英

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?

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.

在Angular 5+中,它的工作方式略有不同:

const number = $event.target.scrollingElement.scrollTop || $event.target.documentElement.scrollTop;

Since some people come via Google to this question:

I'm quite a fan of moving logic like this into something re-useable. For Angular this would mean a directive. Therefore as I run into this issue myself I created a library from my code that at least has some tests and support across many browsers. So feel free to use this tested piece of code instead of polluting your components with more code.

https://w11k.github.io/angular-sticky-things/

With the code I see in the answer I did run into some issues. In another SO I found this solution. It is crucial to determine the offsetY of the header element correctly.

// Thanks to https://stanko.github.io/javascript-get-element-offset/
function getPosition(el) {
  let top = 0;
  let left = 0;
  let element = el;

  // Loop through the DOM tree
  // and add it's parent's offset to get page offset
  do {
    top += element.offsetTop || 0;
    left += element.offsetLeft || 0;
    element = element.offsetParent;
  } while (element);

  return {
    y: top,
    x: left,
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM