Detect Screen Orientation in ionic2/Angular2

The change to the typings file? Go to

node_modules\ionic-native\dist\es5\plugins\screen-orientation.d.ts

and change:

static orientation: string;

to:

static orientation: any;
1 Like

Hi dwhite97,
I have changed static orientation: string; to ‘any’ but still it is undefined only

Have you installed and saved the plugin?

$ ionic plugin add cordova-plugin-screen-orientation --save

If not, I’m not sure.

Hi,
yaaa i have installed

Hi,
Here is my code.can you please check

import { ScreenOrientation } from ‘ionic-native’;
@Component({
templateUrl: ‘app.html’
})
export class IES {
constructor(public platform: Platform){}
window.addEventListener(“orientationchange”, function(){
console.log(‘New screen orientation:’, ScreenOrientation.orientation.type)

});
}

If you’re using the cordova plugin and since you’re making mobile apps, and cordova is the bridge needed to use phone’s hardware, you can’t test this on any browser. Try deploying on a real device or an emulator. Check this: Ionic 2 | Deploying

Funnily enough, I was able to test this on a browser (Chrome). Despite using the Cordova plugin.

I have no idea why, unfortunately.

Hi,

I managed to get this with the following:

import { AfterContentChecked, OnDestroy, ChangeDetectorRef } from '@angular/core';

class Page implements AfterContentChecked, OnDestroy {

  isPortrait: boolean;
  timeouts: number[];

  ...

  ngAfterContentChecked(): void {
    if (window.matchMedia("(orientation: portrait)").matches) {
      this.isPortrait = true;
    } else {
      this.isPortrait = false;
    }
    // forcing Angular to detect the changes
    this.timeouts.push(setTimeout(() => this.changeDetectorRef.detectChanges(), 100));  
  }

  ngOnDestroy() {
    this.timeouts.forEach( (val) => clearTimeout(val) );
  }
}

An isPortrait can then be used in your templates.

I’m not sure how long this has been in Ionic, but I found hidewhen/showwhen attribute when reviewing the API docs https://ionicframework.com/docs/api/components/show-hide-when/HideWhen/
https://ionicframework.com/docs/api/components/show-hide-when/ShowWhen/
That can be used for orientation as well as platform specific conditioning of markup. I hope it helps anyone else who Googles in on this topic in future too.

1 Like