Changing UI Dynamically: BreakpointObserver

Utkarsh Chakravarty
The Startup
Published in
3 min readMay 10, 2020

Explaining how to make your Angular application respond dynamically according to different screen sizes

Struck with the problem of how to make your webApp responsive to all the screen sizes? No worries, here is the solution to it.

Many of us want to render different elements for different screen sizes to make our WebApp look more appropriate. There can be many ways to achieve this but here I present the simplest way to do it. So let's start…

Setup your Angular project using the following command:

Install Angular Material

Use the Angular CLI’s install schematic to set up your Angular Material project by running the following command:

API reference for Angular CDK layout

We will use the CDK layout to use the BreakpointObserver service provided in this module. Now, import the LayoutModule in app.module.ts

Generate a component

Generate a new component if you have not created one using the Angular CLI:

Now move to test.component.ts file and use the BreakpointObserver service to make your design act according to different screen sizes.

Using BreakpointObserver Service

BreakpointObserver is a utility for checking the matching state of @media queries. It has two methods:

  • isMatched: Whether one or more media queries match the current viewport size.
  • observe: Gets an observable of results for the given queries that will emit new results for any changes in matching of the given queries.

To get it on Init:

If you want to keep it updated on resize:

In Angular, the @HostListener() function decorator allows you to handle events of the host element in the directive class.

Whenever the event is emitted, it will automatically detect and render the component according to the instructions(set of programs). Here we use ‘window: resize’ event which activates when the screen size is changed so it will help you to make your WebApp responsive by using ‘isSmallScreen’ variable which is of boolean type in the following manner mentioned below. In this example I have mentioned only a single screen size, you have the freedom to mention your various breakpoints according to your need and it will work fine.

Now move to test.component.html

*ngIf is a structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. So you can write your code accordingly inside the respective container and it will display accordingly on different screen sizes.

Now, serve your project and test it

Take a look at an example of this code

Thank You for reading!

--

--