Ionic 3 Screen Orientation Example


Notice: A non well formed numeric value encountered in /home/ghadeerr/public_html/ghadeer.io/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 118

 

Depending on the type of application being written, we may want to force our app to a specific orientation. In other instances, we may want to detect changes to the orientation and perform some action.

Ionic Native gives us the ability to do both of these using the screen orientation plugin.

We’ll get started by creating a blank ionic project

Next, we’ll add the cordova plugin and install the ionic native wrapper.

The Ionic 3 app we are going to write will have 3 buttons

1. Lock Landscape – This will lock the orientation to landscape.
2. Lock Portrait – This will lock the orientation to portrait.
3. Unlock – This will unlock any orientation locks. In other words, if we had locked our app to support only portrait mode, we will now be able to switch back and forth between portrait and landscape.

We’ll start by writing out the template and, to make the process easier, we are going to use the home.ts file that was generated by the ionic-cli.

You can see here that we have 3 buttons, each with their respective function. Now let’s create our component:

We have injected ScreenOrientation which we will use to interact with all of our screen orientation functions.

Now let’s implement the lockLandscape function:

When this function is invoked, we call ScreenOrientation and lock the orientation to Landscape mode which will always show Landscape. Note that ORIENTATIONS is simply an enum and ORIENTATIONS.LANDSCAPE is a string value. We could have written the following and achieved the same results.

The lockPortrait function is identical to the lockLandscape function (other than the value we pass to the lock function).

We have the ability to force the orientation to either portrait or landscape, but cannot freely switch between the two. Let’s write an unlock function that can help.

Finally we’ll subscribe to change events, so that we can react to orientation change events. We’ll put the change event in the ionViewDidLoad function so that we capture it when the page has finished loading.

One last thing to note, we can get the current orientation by type property (we’ll update the alert to reflect this).

You can see below the entire completed component.

The last thing to take note of is we are doing this in our component, this type of logic should really be moved to a service, it’s just much easier to demonstrate this functionality in a component; components should only be responsible for the presentation logic and nothing more.

You can see the video of this tutorial below so you can review the entire process again:

If you enjoyed this article, enter your email below to get free updates!