How To Detect Window width in Angular

Sometimes, you might need to perform the tasks depending on the particular window size, it could be anything for instance adding a class, adding styling, or any function call. here below blog useful.

Add below lines in app.component.html

    <h4>Detect Width Of Window</h4>
    <p>Window Width: {{ width }}</p>
    <p>Mobile: {{ isMobile }}</p>
    <p>Other Device: {{ !isMobile }}</p>

Add below lines in app.component.ts

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

function _window(): any {
  return window;

export class WindowRef {
  get nativeWindow(): any {
    return _window();

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  host: {
    '(window:resize)': 'onWindowResize($event)',
export class AppComponent {
  windowSize: any;
  isMobile: boolean = false;
  width: number = window.innerWidth;
  height: number = window.innerWidth;
  mobileWidth: number = 760;

  ngOnInit(): void {
    this.isMobile = this.width < this.mobileWidth;

  onWindowResize(event:any) {
    this.width =;
    this.height =;
    this.isMobile = this.width < this.mobileWidth;

Now, run the application using npm start :

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories