How to get device width and height in Ionic using TypeScript?

AngularTypescriptIonic FrameworkIonic2Ionic3

Angular Problem Overview


I am trying to get device width and height in ionic 2 using typescript.

In previous version of ionic 2 I used,

window.screen.width
window.screen.height

but in newer version this is not working.

How it is work with Type Script + ionic 2?

Angular Solutions


Solution 1 - Angular

You can use the Platform information for this.

Internally the platform uses the window.innerWidth and window.innerHeight but

> Using this method is preferred since the dimension is a cached value, > which reduces the chance of multiple and expensive DOM reads.

Ionic 4/5

Docs: https://ionicframework.com/docs/angular/platform#width-number

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

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

Ionic 2/3

Docs: https://ionicframework.com/docs/v3/api/platform/Platform/#width

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

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

Solution 2 - Angular

Try using window.innerHeight and window.innerWidth to get height and width of the device respectively.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJignesh M. MehtaView Question on Stackoverflow
Solution 1 - AngularsebaferrerasView Answer on Stackoverflow
Solution 2 - AngularAishAppView Answer on Stackoverflow