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)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!