Skip to main content

Working with Platform Services

1. Detecting Platform

Platform Detection Method Notes
Web platform.is('web') Runs in a web browser
Mobile Web platform.is('mobileweb') Mobile browser (iOS/Android) in web view
iOS platform.is('ios') iOS device or simulator
Android platform.is('android') Android device or emulator
Desktop platform.is('desktop') Desktop browser (Chrome, Firefox, Safari)
Electron platform.is('electron') Electron app (desktop)

Example: Detecting Platform

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

async function detectPlatform() {
  if (platform.is('ios')) {
    console.log('Running on iOS device');
  } else if (platform.is('android')) {
    console.log('Running on Android device');
  } else if (platform.is('web')) {
    console.log('Running in web browser');
  }
}
Note: Use platform.is() to detect the current platform at runtime. This is useful for applying platform-specific styling or behavior.

2. Checking Platform Ready

Use the Platform service to check if the platform is ready before performing operations that depend on native capabilities.

Method Description Return Type Notes
isReady() Checks if the platform is ready for native operations. Promise<boolean> Returns true if the platform is ready, otherwise false.

Example: Checking Platform Ready

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html'
})
export class HomePage implements OnInit {

  constructor(private platform: Platform) {}

  async ngOnInit() {
    const isReady = await this.platform.isReady();
    if (isReady) {
      console.log('Platform is ready');
    } else {
      console.log('Platform is not ready yet');
    }
  }
}
Note: The isReady() method is particularly useful when working with Cordova plugins or native device APIs that require the platform to be fully initialized.

3. Using Platform-Specific Code

Example: Platform-specific code in Ionic

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

constructor(private platform: Platform) {
  if (this.platform.is('android')) {
    console.log('Running on Android');
  } else if (this.platform.is('ios')) {
    console.log('Running on iOS');
  } else {
    console.log('Running on web or other platform');
  }
}
Platform Check Method Description
android platform.is('android') Checks if the app is running on Android
ios platform.is('ios') Checks if the app is running on iOS
cordova platform.is('cordova') Checks if the app is running in Cordova/PhoneGap
capacitor platform.is('capacitor') Checks if the app is running in Capacitor
mobile platform.is('mobile') Checks if the app is running on a mobile device
mobileweb platform.is('mobileweb') Checks if the app is running on a mobile web browser
Note: The platform.is() method returns a boolean indicating whether the app is running on the specified platform.

Example: Using device-specific APIs

import { Platform } from '@ionic/angular';
import { Camera } from '@awesome-cordova-plugins/camera/ngx';

constructor(private platform: Platform, private camera: Camera) {
  if (this.platform.is('cordova')) {
    this.camera.getPicture().then((imageData) => {
      // Handle image data
    });
  }
}

Platform-Specific Code Best Practices

  • Use platform.is() to detect the current runtime environment
  • Wrap platform-specific code in conditional blocks to avoid errors on unsupported platforms
  • Test your app on all target platforms to ensure compatibility
  • Use Capacitor or Cordova plugins for native device features

4. Detecting Device Orientation

Property Description Values
orientation Current device orientation portrait, landscape
isLandscape Boolean indicating landscape mode true, false
isPortrait Boolean indicating portrait mode true, false

Example: Check Orientation

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

constructor(private platform: Platform) {
  this.platform.ready().then(() => {
    console.log('Orientation:', this.platform.orientation);
    console.log('Is Landscape:', this.platform.isLandscape());
    console.log('Is Portrait:', this.platform.isPortrait());
  });
}
Note: Orientation changes are not automatically detected. You must manually check or listen for changes using window.addEventListener.

5. Getting Platform Platforms

Platform Identifier Description
web web Web browser environment
mobile-web mobile-web Mobile web browser (iOS/Android)
android android Android device or emulator
ios ios iOS device or simulator
electron electron Desktop app using Electron
capacitor capacitor Capacitor-based hybrid app
cordova cordova Cordova-based hybrid app

Example: Detecting Platform

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

const platform = Platform.platforms();
console.log(platform); // e.g. ['mobile-web', 'ios']

6. Handling Keyboard Events

Event Description Usage
keydown Fires when a key is pressed down document.addEventListener('keydown', (e) => { ... });
keyup Fires when a key is released document.addEventListener('keyup', (e) => { ... });
keypress Fires when a key is pressed and released (deprecated) document.addEventListener('keypress', (e) => { ... });

Example: Listening for Escape Key

document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') {
    console.log('Escape key pressed');
  }
});

Example: Preventing Default Behavior

document.addEventListener('keydown', (e) => {
  if (e.key === 'Tab') {
    e.preventDefault(); // Prevents default tab behavior
  }
});
Note: In Ionic apps, keyboard events may behave differently on mobile devices due to platform-specific handling.

7. Managing Status Bar

Property Description Values
backgroundColor Sets the background color of the status bar #ffffff
styleDefault Applies default status bar style (light content) true
styleLightContent Applies light content style (dark text) true
styleDarkContent Applies dark content style (light text) true
hide Hides the status bar true

Example: Configure Status Bar

import { StatusBar } from '@ionic-native/status-bar';<br><br>StatusBar.setbackgroundColor('#3880ff');<br>StatusBar.setStyle(StatusBar.styles.LightContent);<br>StatusBar.hide();
Note: The Status Bar plugin requires the cordova-plugin-statusbar to be installed.

8. Using Safe Area Insets

Safe area insets are crucial for ensuring content is properly positioned on devices with notches, rounded corners, or other screen cutouts. Ionic provides utilities to help developers handle these insets effectively.

Property Description Values
safe-area-top Top inset value for safe area 0px to 100px+
safe-area-bottom Bottom inset value for safe area 0px to 100px+
safe-area-left Left inset value for safe area 0px to 100px+
safe-area-right Right inset value for safe area 0px to 100px+

Example: Applying Safe Area Insets in CSS

.content {
  padding-top: env(safe-area-inset-top);
  padding-bottom: env(safe-area-inset-bottom);
  padding-left: env(safe-area-inset-left);
  padding-right: env(safe-area-inset-right);
}

Example: Using Ionic's Built-in Safe Area Classes

<ion-content class="ion-padding">
  <div class="safe-area-container">
    <h2>Content Area</h2>
  </div>
</ion-content>
Note: The env() function is supported in modern browsers and can be used to access safe area values directly in CSS.

9. Detecting RTL Layout

Property Description Usage
isRTL Indicates if the current layout direction is Right-To-Left isRTL is a boolean property from the Platform service.

Example: Checking RTL Layout

import { Component } from '@angular/core';<br>import { Platform } from '@ionic/angular';<br><br>@Component({<br>  selector: 'app-example',<br>  template: ''<br>})<br>export class ExampleComponent {<br>  constructor(private platform: Platform) {}<br><br>  ngOnInit() {<br>    if (this.platform.isRTL) {<br>      console.log('RTL layout detected');<br>    } else {<br>      console.log('LTR layout detected');<br>    }<br>  }<br>}
Note: The isRTL property is determined by the browser's language settings and CSS direction properties.

10. Handling Back Button

Property Description Usage
ionBackButton Customizes the back button behavior in Ionic apps. <ion-back-button></ion-back-button>
defaultHref Defines the default URL to navigate to when the back button is pressed. <ion-back-button defaultHref="/home"></ion-back-button>
icon Overrides the default back icon with a custom one. <ion-back-button icon="arrow-back"></ion-back-button>
text Customizes the text displayed next to the back icon. <ion-back-button text="Go Back"></ion-back-button>

Example: Custom Back Button

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button defaultHref="/home"></ion-back-button>
    </ion-buttons>
    <ion-title>Back Button Example</ion-title>
  </ion-toolbar>
</ion-header>
Note: The ion-back-button component is automatically handled by Ionic's navigation stack, but can be customized for specific use cases.

Was this article helpful?