93

I found this solution. Is it valid?

import {Component} from '@angular/core';
import {Platform} from 'ionic-angular';

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

This solution is for ionic 2. can i also used for angular 2?

Please suggest me the right way to do it.

BlackBeard
  • 10,246
  • 7
  • 52
  • 62
Harish Mahajan
  • 3,254
  • 4
  • 27
  • 49

6 Answers6

155

For those who want to get height and width of device even when the display is resized (dynamically & in real-time):

  • Step 1:

In that Component do: import { HostListener } from "@angular/core";

  • Step 2:

In the component's class body write:

@HostListener('window:resize', ['$event'])
onResize(event?) {
   this.screenHeight = window.innerHeight;
   this.screenWidth = window.innerWidth;
}
  • Step 3:

In the component's constructor call the onResize method to initialize the variables. Also, don't forget to declare them first.

constructor() {
  this.onResize();
}    

Complete code:

import { Component, OnInit } from "@angular/core";
import { HostListener } from "@angular/core";

@Component({
  selector: "app-login",
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class FooComponent implements OnInit {
    screenHeight: number;
    screenWidth: number;

    constructor() {
        this.getScreenSize();
    }

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

}
ChadESmith42
  • 23
  • 1
  • 6
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
  • how about minimum height (min-height)? – Artanis Zeratul Feb 27 '19 at 04:06
  • 1
    screenHeight:any; screenWidth:any; they are numbers ;) – tibi Mar 06 '19 at 09:43
  • 1
    This explanation helped so much. I was also able to switch the expand/collapse by testing for width breakpoint in the HostListener width change event. Perfect! – Connie H. May 08 '19 at 02:36
  • @BlackBeard : why is that questionmark in function definition after event ? i.e. getScreenSize(event?) . I am unaware about it. is it a practice? – omkar Oct 20 '19 at 17:59
  • 2
    @omkar Angular2+ uses Typescript; In Typescript a questionmark (?) can be used in method signature like shown to mark optional parameters. In this example HostListener will provide event (I guess it has been provided just for sake of completeness - you dont need to forward in this example) and the initial call from constructor will not provide event. If you omit marking optionality while it is needed the typescript compiler in IDE or maybe ng-build later-on could throw warning / error about signature discrepancy. – David Renner Jun 01 '20 at 16:43
  • Should change the function name to setScreenSize. – Sirar Salih Dec 28 '20 at 12:10
  • is it possible to get the device's status bar height? am trying to do a sticky navbar (already has `z-index` set, and `top` set based on some `viewport`). however, it's still acting funky and awkward – domster Jul 17 '22 at 02:49
77

I found the solution. The answer is very simple. write the below code in your constructor.

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

@Component({
  selector: "app-login",
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit, OnDestroy {
    // Declare height and width variables
    scrHeight:any;
    scrWidth:any;

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

    // Constructor
    constructor() {
        this.getScreenSize();
    }


}

====== Working Code (Another) ======

export class Dashboard  {
 mobHeight: any;
 mobWidth: any;
     constructor(private router:Router, private http: Http){
        this.mobHeight = (window.screen.height) + "px";
        this.mobWidth = (window.screen.width) + "px";
          console.log(this.mobHeight);
          console.log(this.mobWidth)
     }
}
Harish Mahajan
  • 3,254
  • 4
  • 27
  • 49
  • show, thanks , work with angular 12 and ionic 6 – Wellington Alves Mar 23 '22 at 18:00
  • What is the type of the 'event?' parameter inside getScreenSize? In Angular 13, it doesn't compile unless I explicitely pass event?: any (or maybe it is because of some settings I have). Also, as it is not used inside the function, is it even required? – Raphael Pinel Jun 13 '22 at 11:11
30
export class Dashboard {
    innerHeight: any;
    innerWidth: any;
    constructor() {
        this.innerHeight = (window.screen.height) + "px";
        this.innerWidth = (window.screen.width) + "px";
    }
}
Community
  • 1
  • 1
Bhavan Patel
  • 1,755
  • 1
  • 16
  • 30
10

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

public get height() {
  return window.innerHeight;
}

public get width() {
  return window.innerWidth;
}

And use that in template like this:

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

Print the value

console.log(this.height, this.width);

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

Rohan Gayen
  • 375
  • 1
  • 4
  • 11
7

Keep in mind if you are wanting to test this component you will want to inject the window. Use the @Inject() function to inject the window object by naming it using a string token like detailed in this duplicate

Community
  • 1
  • 1
Strake
  • 702
  • 1
  • 8
  • 18
0

I've read that it's recommended that you Inject DOCUMENT in the constructor so it works on both rendering platforms: browser and server side. The global DOM reference to window only works for browser rendering platforms. To get access to the widow object you can use DOCUMENT:

@Inject(DOCUMENT) private _document: Document

console.log('window height ', this._document.defaultview.innerHeight);
console.log('window height ', this._document.defaultview.innerWidth);
Crystal
  • 1,425
  • 1
  • 22
  • 34