Skip to main content

Let’s build a breakpoint observer with RxJS and media queries, that means a small service that provides the current page width via specially defined media queries.

TL;DR
Angular service which listens at a central point to changes in window size and returns a value e.g. [s, m, l, xl] within an observable based on media queries.

Stackblitz playground
https://stackblitz.com/edit/angular-7-breakpoint-observer

The example

In the course of time I came again and again to the point where it was very difficult to design elements responsive via CSS, especially when using external components from libraries or frameworks.

I am using an external component, written by another developer, e.g. a slider to display articles, depending on the screen size the number of articles should vary.

The number of articles in the slider is defined via a JavaScript object, this object is passed to the external component, in this case the slider.

The problem

The slider, performs a series of checks based on the number of articles transferred and the current screen width. For example, the width of the articles within the sliders or their distance from each other. This makes it very difficult to define the number of articles afterwards via CSS, or even impossible without a headache. But we need to!

In simple terms
This means I need to know the maximum number of articles in my JavaScript or TypeScript class based on the current screen size in order to pass them to the slider component.

The solution

It would be great if you could define a range e.g. between 301px and 600px
we need 3 articles, between 601px and 900px we need 5 articles and everything above is filled with 6 articles.

Maybe something like this?
A service which checks if the media query for example “min-width: 575px” has been overstepped or understepped and only fires an observable if there is a relevant change.

Thus, in our class, which calls the external component, we can define the configuration object for the slider (see graphic above) based on the returned value within the observable from our new angular-breakpoint-observer service.