This is an old post so my answer is for Angular 9+, this answer is tested on Angular 15
I've handled scrolling events in Angular with the Renderer2 Class listening for a scroll event on a DOM element.
Then, using a simple class to make the styling changes.
Like this.
Add an ID to the DOM element (in your HTML template) that you want to manipulate, and the DOM element you want to listen to (if not the window element).
inject Renderer2 into you component constructor
constructor(private renderer: Renderer2) { }
In your ngOnInit, define a reference to the DOM elements you want to change & the element to want render2 to listen to.
const addBtn : HTMLElement | any = document.getElementById('addBtn');
const gridView : HTMLElement | any = document.getElementById('gridView');
...in this example its not the Document "Window", but a scrollable fixed height div, I'm listening to for scrolling changes.
Next add this block of code. Mine is actually firing on an Input change so will be in ngOnChanges, but yours might be in AfterViewInit. You'll need to experiement, but all DOM elements must be rendered so that your references to them won't be undefined.
this.renderer.listen(gridView, 'scroll', (event) => {
const number = event.target.scrollTop;
if (number > 200 ) {
addBtn.classList.add('showCompactBtn');
} else {
addBtn.classList.remove('showCompactBtn');
}
});
So what's happening here... First I instruct the renderer to listen for the "scroll" event in the DOM element "gridview" (which I defined earlier), but this could be 'window' if you wanted to listen to that.
Next, I get the scrolltop position from the returned renderer event.
Finally, setting a class to the target element when the scrolltop reaches a certain threshold.
You would then need to define the styling changes that the added class would effect in your CSS/SCSS
That's it. This is a bare bones with lots of room for improvement.