Does your Angular application need to know the user's screen size from time to time?

If so, you're not alone. There's often a requirement for that kind of logic.

That's because we live in the Mobile Epoch of the Information Age. Everything is mobile now.

Well, almost everything. Some people still prefer their huge desktop screens.

And so you need to accommodate both groups of people.

Usually, that's accomplished on the client side with responsive CSS and a 12-column layout. 

But in Angular applications there are instances where you need to rely on TypeScript to make the determination on the fly. 

And that's why you're here.

Open a Window

Good news: there's a property called window that's going to give you the screen size. Just grab the innerWidth property.

For example:

let screenSize = window.innerWidth;

Yep. That'll do it.

Then, your application can use the layout logic you provided to display the components based on the width of the screen.

But that's just a single check. Your application might need to "listen" for screen size changes.

Listening In

See, here's the thing: sometimes, users change their screen sizes.

Sure, they can do that by switching orientation or shrinking their browser window size.

When that happens, you'll want your application to react (it's a reactive application after all) to the new screen dimensions.

But you're going to need some kind of "listener" to make that happen.

Fortunately, one such listener exists: @HostListener.

It's a decorator, as you can see from the @ sign. And it can listen for various DOM events, not just screen size changes.

But here we're interested in screen size changes. So let's look at how to make that happen.

  @HostListener('window:resize', ['$event'])
  onResize(event) {

That's a bit of awkward syntax but it gets the job done.

The application will listen for window resizing events. Once that happens, it triggers the onResize() method that you see above.

You can put whatever code you want in that method. In the example here, the application invokes the respondToScreenSizeChange() method with the new size of the screen. 

Now the application can respond to the new screen size by laying out the UI elements differently.

And that is, of course, exactly the kind of behavior you're looking for with this kind listener.

Wrapping It Up

Awesome. Now you know how to listen for screen size changes in your Angular application.

Feel free to use the code above as you see fit. Modify it to suit your requirements.

Have fun!