[html] Detecting real time window size changes in Angular 4

I have been trying to build a responsive nav-bar and do not wish to use a media query, so I intend to use *ngIF with the window size as a criterion. But I have been facing a problem as I am unable to find any method or documentation on Angular 4 window size detection. I have also tried the JavaScript method, but it is not supported.

I have also tried the following:

constructor(platform: Platform) {
    platform.ready().then((readySource) => {
        console.log('Width: ' + platform.width());
        console.log('Height: ' + platform.height());

...which was used in ionic.

And screen.availHeight, but still no success.

This question is related to html angular dom-events

The answer is

@HostListener("window:resize", [])
public onResize() {

public ngAfterViewInit() {

private detectScreenSize() {
    const height = window.innerHeight;
    const width = window.innerWidth;

If you want to react on certain breakpoints (e.g. do something if width is less than 768px), you can also use BreakpointObserver:

import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';

{ ... }

const isSmallScreen = breakpointObserver.isMatched('(max-width: 599px)');

or even listen to changes to that breakpoint:

  '(max-width: 768px)'
    ]).subscribe(result => {
      if (result.matches) {
      } else {
        // if necessary:

The documentation for Platform width() and height(), it's stated that these methods use window.innerWidth and window.innerHeight respectively. But using the methods are preferred since the dimensions are cached values, which reduces the chance of multiple and expensive DOM reads.

import { Platform } from 'ionic-angular';

private width:number;
private height:number;

constructor(private platform: Platform){
    platform.ready().then(() => {
        this.width = platform.width();
        this.height = platform.height();

You may use the typescript getter method for this scenario. Like this

public get width() {
  return window.innerWidth;

And use that in template like this:

<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768 

You won't need any event handler to check for resizing/ of window, this method will check for size every time automatically.

If you'd like you components to remain easily testable you should wrap the global window object in an Angular Service:

import { Injectable } from '@angular/core';

export class WindowService {

  get windowRef() {
    return window;


You can then inject it like any other service:

    private windowService: WindowService
) { }

And consume...

  ngOnInit() {
      const width= this.windowService.windowRef.innerWidth;

you can use this https://github.com/ManuCutillas/ng2-responsive Hope it helps :-)

This is an example of service which I use.

You can get the screen width by subscribing to screenWidth$, or via screenWidth$.value.

The same is for mediaBreakpoint$ ( or mediaBreakpoint$.value)

import {
} from '@angular/core';
import {
} from 'rxjs';
import {
} from 'rxjs/operators';

export class ResponsiveService implements OnDestroy {
  private _unsubscriber$: Subject<any> = new Subject();
  public screenWidth$: BehaviorSubject<number> = new BehaviorSubject(null);
  public mediaBreakpoint$: BehaviorSubject<string> = new BehaviorSubject(null);

  constructor() {

  init() {
    fromEvent(window, 'resize')
      ).subscribe((evt: any) => {

  ngOnDestroy() {

  private _setScreenWidth(width: number): void {

  private _setMediaBreakpoint(width: number): void {
    if (width < 576) {
    } else if (width >= 576 && width < 768) {
    } else if (width >= 768 && width < 992) {
    } else if (width >= 992 && width < 1200) {
    } else if (width >= 1200 && width < 1600) {
    } else {


Hope this helps someone

The answer is very simple. write the below code

import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";

 selector: "app-login",
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']

export class LoginComponent implements OnInit, OnDestroy {
// Declare height and width variables

@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
      this.scrHeight = window.innerHeight;
      this.scrWidth = window.innerWidth;
      console.log(this.scrHeight, this.scrWidth);

// Constructor
constructor() {

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to dom-events

Detecting real time window size changes in Angular 4 Does Enter key trigger a click event? What are passive event listeners? Stop mouse event propagation React onClick function fires on render How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over iFrame onload JavaScript event addEventListener, "change" and option selection Automatically pass $event with ng-click? JavaScript click event listener on class