Ionic 5 Set Screen Orientation in LANDSCAPE/ PORTRAIT and Lock/ Unlock using Ionic Native Plugin

In this Ionic 5/4 tutorial, we’ll learn how to control screen orientation on an Ionic application into a Landscape or Portrait mode forcing and enforcing screen rotation using Cordova and Native plugins. In an Ionic application, we can easily force orient screen into Landscape or Portrait mode. In some situations developers need to show UI of application in a specific layout, this plugin can help to lock/ unlock screen orientation by calling some simple methods. Here we will create a new Ionic application and Install Ionic’s Screen Orientation Plugin with Cordova wrapper to access hardware features. Let’s start…

Install or Update Ionic CLI

To create Ionic applications, you need to install @ionic/cli package. If already have updated it to the latest version

$ npm install -g @ionic/cli

Create new Ionic Angular Application

We’ll create a new Ionic 5 application using Angular framework with a starter blank template.

$ ionic start ionic-vibration-plugin-app blank --type=angular

The --type option property is used to select the framework we want to use for our Ionic application   Move to the application directory  
$ cd ionic-vibration-plugin-app
Now you can run the Ionic application by hitting  
$ ionic serve --lab
The--lab option is used to open the application in the browser into a lab viewer where you can concurrently see how it will look on multiple platforms including Android, iOS, and Windows.  

Install Cordova and Native Screen Orientation Plugin

After creating and moving to the app folder in CLI we will install Cordova and Ionic native plugin to work in the application. Run following CLI commands to install the Cordova and Ionic native plugin.
$ ionic cordova plugin add cordova-plugin-screen-orientation
$ npm install @ionic-native/screen-orientation

Import Plugin in App’s Module

After successful installation of Cordova and Native plugin, open app.module.ts file then import and add the plugin in the providers array
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    ScreenOrientation,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Using the Screen Orientation Plugin in Home Component

To use the plugin we will import it then add in the constructor of component.
import { Component } from '@angular/core';

import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(private screenOrientation: ScreenOrientation) {}

}
 

How to Get Current Screen Orientation?

To get the current Orientation of Screen, use <strong>type</strong>this will return the string value.
// get current
// logs the current orientation, example: 'landscape'
this.currentScreenOrientation = this.screenOrientation.type;
 

Lock a Screen Orientation

To Set Orientation in Landscape or Portrait call lock() method as shown below
  setLandscape(){
    // set to landscape
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE);
  }

  setPortrait(){
    // set to portrait
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
  }
 

Unlock a Screen Orientation

Similarly, we can Unlock the locked orientation by calling <strong>unlock()</strong> method to enable users to apply their own orientation.
  unlockScreen(){
    // allow user rotate
    this.screenOrientation.unlock();
  }
 

Update Home Class

After combining all methods above our home.page.ts file will look like this
import { Component } from '@angular/core';

import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  currentScreenOrientation:string;


  constructor(private screenOrientation: ScreenOrientation) {
    // get current
    this.currentScreenOrientation = this.screenOrientation.type; // logs the current orientation, example: 'landscape'

    // detect orientation changes
    this.screenOrientation.onChange().subscribe(
      () => {
        alert("Orientation Changed"+this.screenOrientation.type);
        this.currentScreenOrientation = this.screenOrientation.type;
      }
    );
  }

  setLandscape(){
    // set to landscape
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE);
  }

  setPortrait(){
    // set to portrait
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
  }

  unlockScreen(){
    // allow user rotate
    this.screenOrientation.unlock();
  }

}
 

Update Home Template

To call these methods to change the home.page.html file with the following code.
<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic 4 Screen Orientation
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>

  <ion-list>
    <ion-item>
      Current Screen Orientation: <strong>{{this.currentScreenOrientation}}</strong>
    </ion-item>
    <ion-item>
      <ion-button (click)="setLandscape()">
        Set Landscape
      </ion-button>
    </ion-item>
    <ion-item>
      <ion-button (click)="setPortrait()">
        Set Portrait
      </ion-button>
    </ion-item>
    <ion-item>
      Unlock Screen Orientation: <ion-button (click)="unlockScreen()">
        Unlock
      </ion-button>
    </ion-item>
  </ion-list>

</ion-content>
 

Conclusion

That’s we have successfully implemented the Screen Orientation plugin in the Ionic application, to test this plugin you need to run the app in a real device. You can easily control screen direction for specific interface requirement using this plugin provides most of the plugins required to handle screen orientation in IOS, Android, and Windows.    

2 thoughts on “Ionic 5 Set Screen Orientation in LANDSCAPE/ PORTRAIT and Lock/ Unlock using Ionic Native Plugin”

  1. core.js:4197 ERROR Error: Uncaught (in promise): NotSupportedError: screen.orientation.lock() is not available on this device.
      at resolvePromise (zone-evergreen.js:798)
      at zone-evergreen.js:705
      at ZoneDelegate.invoke (zone-evergreen.js:364)
      at Object.onInvoke (core.js:27437)
      at ZoneDelegate.invoke (zone-evergreen.js:363)
      at Zone.run (zone-evergreen.js:123)
      at zone-evergreen.js:857
      at ZoneDelegate.invokeTask (zone-evergreen.js:399)
      at Object.onInvokeTask (core.js:27425)

    •   at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    1. Yuriy Krasnokutskiy

      That means you’re trying to run this code on not supported device (like browser).
      Try it on Android device or iOS

Leave a Comment

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