DEV Community

sekab
sekab

Posted on

How to act properly to scroll to bottom behavior using RxJS

Hi, I'm Amr Taher, a cross-platform software engineer who loves coding in Javascript and greatly appreciates clean modular techniques to make your application maintainable and scalable.

Ever wondered on how would you act when the user scrolls to the bottom in an Angular application ? for example if you have like 3 Components that triggers some action whenever the user scrolls to the bottom (getting more data or changing some styling), how would you do that?

rxjs provides a very powerful toolkit that you could use in order to achieve a clean approach to such a problem.

First, let us listen to the user's scroll behaviour and check if he is at the bottom in the AppComponent.ts

    window.onscroll = () => {
      const d = document.documentElement;
      const offset = d.scrollTop + window.innerHeight;
      const height = d.offsetHeight;
      if (offset === height) {
        // do some action here.
      }
    };

Now whenever the user is at the bottom the condition above will be triggered.
We can use rxjs powerful tools to use this event to share such scroll behaviour in the desired components.

In A service lets say a ThemingService

public isAtBottom$ = new BehaviourSubject<Boolean>(false);

Here we defined a behaviour subject that we can listen to in any of the components through subscribing to it!

if (offset === height) {
this.theming.isAtBottom$.next(true);
}

now we trigger the behaviour subject to true whenever we reach the bottom.

In any components, we can simply subscribe to the behaviour subject to trigger the desired events we want whenever we are at the bottom.

ComponentA

this.theming.isAtBottom$.subscribe(res => {
if (res) {
// do something
});

And that is it! I hope you guys like the idea, you can pretty much do this in any component now while only listening to the scroll event in one section (AppComponent.ts)

Top comments (0)