maguilleng maguilleng - 8 months ago 98
TypeScript Question

Ionic 2 ScreenOrientation Plugin Changes

I need your help with this: Two months ago, my Ionic 2 app was working right, using the ScreenOrientation cordova plugin, with this code:



window.addEventListener('orientationchange', ()=>{
console.info('DEVICE ORIENTATION CHANGED!');
console.debug(ScreenOrientation.orientation);
if(ScreenOrientation.orientation.type.indexOf('landscape') !== -1){
this.screenOrientationIsPortrait = false;
} else if(ScreenOrientation.orientation.type.indexOf('portrait') !== -1){
this.screenOrientationIsPortrait = true;
}
});


In a new laptop, I installed the most recent Ionic 2 version, and the most recent version of the cordova ScreenOrientation plugin, and with the same app code, and I´m getting this error in Compile time:


Property 'type' does not exist on type 'string'.


I tried using the examples in the github repository of the ScreenOrientation plugin:

window.addEventListener('orientationchange', ()=>{
console.info('DEVICE ORIENTATION CHANGED!');
console.debug(ScreenOrientation.orientation);
if(screen.orientation.type.indexOf('landscape') !== -1){
this.screenOrientationIsPortrait = false;
} else if(screen.orientation.type.indexOf('portrait') !== -1){
this.screenOrientationIsPortrait = true;
}
});


but with that code, I´m getting this error also in Compile Time:


Property 'orientation' does not exist on type 'Screen'


Both, Ionic 2 and the ScreenOrientation Plugin have been updated recently. Based on my research, It appears a TypeScript error, not an updating versions conflict.

How can I know what is wrong? How can I debug to find the reason of this new errors? Any Ideas? Thanks in advance, I appreciate your help.

Github repo examples: https://github.com/apache/cordova-plugin-screen-orientation

Ionic 2 Examples: https://ionicframework.com/docs/v2/native/screen-orientation/

Answer Source

You can actually detect screen orientation change without adding the plugin too. Use property orientation of type window.

window.addEventListener('orientationchange', () => {
      console.info('DEVICE ORIENTATION CHANGED!');
      console.debug(ScreenOrientation.orientation);
      switch (window.orientation) {
        case -90:
        case 90:
              console.log("Landscape orientation");
              this.screenOrientationIsPortrait = true;
              break;
        case 0:
             console.log("Landscape orientation");
              this.screenOrientationIsPortrait = false;
             break;
      }      
    });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download