In my previous article, I showed you how to create and validate forms in Ionic 2 applications. This time we will discuss how to play with Cordova plugins.
 
For this article, we will use a rather simple plugin called Network Information Plugin.
 
While this is a rather simple procedure, I’m still seeing people asking questions on this topic, so let’s take a look how it’s done.
 
 

Note: If this tutorial was helpful, need further clarification, something is not working or do you have a request for another Ionic post? Furthermore, if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here, again leave me a comment below. I'm here to help you, I expect the same from you. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com, or follow and mention me on twitter (@gajotres). Thanks and have a nice day!

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


 

Table of Contents

 
The Ionic 2 is a complex and sometimes difficult field of study so this article will hardly satisfy all your needs. If you require more information beyond the subject of this article you will probably find it in a list below. Take a look; if there’s a topic not covered there, leave me a comment and I’ll cover it.
 
 

Preparations

 
Before we can begin, make sure you have everything preconfigured for Ionic 2.
 
You should have these:
 
  • Android Environment (or iOS if you’re working on a MacOS)
  • nodeJS
  • Ionic 2
  • Cordova
 
Find more information here: IONIC 2 | INSTALLATION GUIDE if you don’t have a previous Ionic 2 installation or if you never read my previous articles on this topic.
 

1. Update Ionic & Cordova

 
You need to have the latest version of nodeJS, without it, you’ll not be able to install/update Cordova and Ionic appropriately.
 
If you have a previous Ionic/Cordova installation make sure its up to date, older versions may not work with this tutorial. Though latest versions may also mess things up:
 
npm update -g cordova ionic@beta
 
or you can even do it like this:
 
npm install -g cordova ionic@beta
 
I will remove beta keyword once Ionic 2 reach RC status.
 
Warning: Ionic2 is still in alpha status so the final implementation may differ from this code. I will update this article if and when that happens.
 
 
 

2. Create A New Project

 
ionic start Ionic2CordovaExample blank --v2
cd Ionic2CordovaExample
 
Open app directory and remove all content from the pages directory but don’t delete it.
 
Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.
 
Add Android platform:
 
ionic platform add android
 
MacOS users can also add iOS platform:
 
ionic platform add ios
 
 
 

3. Install Cordova Plugin

 
Next line will import and install Network Information Plugin into newly created project:
 
cordova plugin add cordova-plugin-network-information
 

Code

 
Before we begin, let’s take a look at a code example. I will post only relevant code, everything else can be found in a provided GitHub repo example (find it in the last section).
 

home.html

<ion-navbar *navbar>
  <ion-title>
    Info Page
  </ion-title>
</ion-navbar>

<ion-content class="home" padding>
  <button (click)="obtainNetworkConnection()" full>Get Nettwork Connection</button>
</ion-content>
 

home.js

import {Page, Platform} from 'ionic/ionic';

@Page({
  templateUrl: 'build/pages/home/home.html',
})
export class HomePage {
  constructor(platform: Platform) {
    this.platform = platform;
  }

  obtainNetworkConnection() {
    this.platform.ready().then(() => {
	    this.networkState = navigator.connection.type;

	    var states = {};
	    states[Connection.UNKNOWN]  = 'Unknown connection';
	    states[Connection.ETHERNET] = 'Ethernet connection';
	    states[Connection.WIFI]     = 'WiFi connection';
	    states[Connection.CELL_2G]  = 'Cell 2G connection';
	    states[Connection.CELL_3G]  = 'Cell 3G connection';
	    states[Connection.CELL_4G]  = 'Cell 4G connection';
	    states[Connection.CELL]     = 'Cell generic connection';
	    states[Connection.NONE]     = 'No network connection';

	    alert('Connection type: ' + states[this.networkState]);
    });
  }  
}
 

Code Overview

 
If you have a previous Ionic v1 experience you should know that most Cordova plugins require a platform to be ready and available. There’s a simple explanation for this, we can access device hardware only when it’s available, and it’s available when platform ready event triggers.
 
We can easily check this state in these next few steps.
 
First what we need is a Platform service. It’s a set of utility methods that can be used to retrieve the device ready state. In Ionic v1 it looked like this:
 
  ionic.Platform.ready(function(){
    // will execute when device is ready, or immediately if the device is already ready.
  });
 
Because Ionic v2 uses object oriented JavaScript this is how it can be done now; import Platform service:
 
import {Page, Platform} from 'ionic/ionic';
 
Inject it into a designated class constructor:
 
  constructor(platform: Platform) {
    this.platform = platform;
  }
 
Finally, this is how we can check for a platform ready event in Ionic v2:
 
this.platform.ready().then(() => {

}
 
With this in mind, let’s use this knowledge. We’ll check network state on a button click:
 
<button (click)="obtainNetworkConnection()" full>Get Nettwork Connection</button>
 
Click event will trigger obtainNetworkConnection function found in a related home.js class:
 
obtainNetworkConnection() {
	this.platform.ready().then(() => {
		this.networkState = navigator.connection.type;

		var states = {};
		states[Connection.UNKNOWN]  = 'Unknown connection';
		states[Connection.ETHERNET] = 'Ethernet connection';
		states[Connection.WIFI]     = 'WiFi connection';
		states[Connection.CELL_2G]  = 'Cell 2G connection';
		states[Connection.CELL_3G]  = 'Cell 3G connection';
		states[Connection.CELL_4G]  = 'Cell 4G connection';
		states[Connection.CELL]     = 'Cell generic connection';
		states[Connection.NONE]     = 'No network connection';

		alert('Connection type: ' + states[this.networkState]);
	});
} 
 
If we click on a provided button, an application will first wait for a platform ready event to trigger. Only then it will alert network status.
 
Simple as that, you don’t need to worry about injected Cordova plugins, Ionic CLI will take care of everything. Most of these plugins will be available as a global JavaScript objects, you don’t need to inject them into classes, they will work out of a box.
 
For example, some plugins like InAppBrowser will use cordova object but the idea is the same:
 
this.platform.ready().then(() => {
    cordova.InAppBrowser.open("http://www.gajotres.net", "_system", "location=true");
});
 

Deployment

 
Next step, build our application:
 
ionic build android
 
Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.
 
Finally:
 
ionic run android -l -c -s
 

Download The Code

 
Working GitHub repo link can be found below:
 
GitHub
 
 

What to read next

IONIC 2 | Integrate Google Maps
 
 

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.

Blogs worth reading

If you're here looking for information related to the Ionic Framework, you will also like these blogs:






  • Thanks for this. I’ve got the plugin installed correctly in my Ionic 2 app, but TypeScript won’t compile because it can’t find the reference for “Connection” in the states array lines. Any idea how to write the import statement for it as per Platform, Page etc?

    Thanks.

  • Cris

    This example is not working for me the problem is that “property connection does not exist on type Navigator”

  • Alugbin Abiodun

    its not working!!! Still not defined

  • Chayma Omrani

    Not working !! I get this error : Property ‘connection’ does not exist on type ‘Navigator’.
    Any idea how to make it work !

  • There’s already Network and Connection modules in ionic-native. Could you please update this tutorial. Using TypeScript would be nice. Thanks!

  • twicejr

    Guys, this is not typescript 🙂

  • rupal patel

    Can you please provide a tutorial about how to use any third party plugin which is not already in ionic-native?