Ionic Cookbook -Third Edition

By Indermohan Singh , Hoc Phan
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Creating Our First App with Ionic
About this book

Ionic is the preferred choice for JavaScript developers to develop real-time hybrid applications. This book will get you started with Ionic 3.9 and help you create Angular 5 components that interact with templates.

You will work with Ionic components and find out how to share data efficiently between them. You'll discover how to make the best use of the REST API to handle back-end services and then move on to animating your application to make it look pretty. You then learn to add in a local push notification in order to test the app. Then you'll work with Cordova to support native functionalities on both iOS and Android. From there, you'll get to grips with using the default themes for each platform and customizing your own. We then take you through the advanced Ionic features like lazy loading, deep linking, localizing ionic apps etc. Finally, you'll see how best to deploy your app to different platforms.

This book will solve all your Ionic-related issues through dedicated recipes that will help you get the best out of Ionic.

Publication date:
April 2018


Creating Our First App with Ionic

In this chapter, we will cover the following topics:

  • Setting up a development environment
  • Creating a HelloWorld app via the CLI
  • Creating a HelloWorld app via Ionic Creator
  • Viewing the app using your web browser
  • Viewing the app using the Ionic CLI
  • Viewing the app using Xcode for iOS
  • Viewing the app using Genymotion for Android
  • Viewing the app using Ionic View


There are many options for developing mobile applications today. Native applications require a unique implementation for each platform, such as iOS, Android, and Windows phone. It's required in some cases, such as high-performance CPU and GPU processing with lots of memory consumption. Any application that does not need over-the-top graphics and intensive CPU processing could benefit greatly from a cost-effective, write once and run anywhere HTML5 mobile implementation.

For those who choose the HTML5 route, there are many great choices on the market. Some options may be very easy to start, but they could be very hard to scale or could face performance problems. Commercial options are generally expensive for small developers to find product/market fit. The best practice is to think of the users first. There are instances where a simple, responsive website design is the best choice; for example, when a business mainly has fixed content with minimal updating required or the content is better off on the web for SEO purposes.

The Ionic Framework has several advantages over its competitors, as shown:

  • Ionic is based on Angular, which is a robust framework for application development. You have all the components to structure and create an application built into it.
  • UI performance is strong because of its usage of the requestAnimationFrame() technique.
  • It offers a beautiful and comprehensive set of default styles, similar to a mobile-focused twitter Bootstrap.
  • Sass is available for quick, easy, and effective theme customization.

There have been many significant changes between the launch of AngularJS 1.x and Angular. All of these changes are applicable to Ionic as well. Consider the following examples:

  • Angular utilizes TypeScript, which is a superset of the ECMAScript 6 (ES6) standard, to build your code into JavaScript. This allows developers to leverage TypeScript features such as type checking during the compilation step.
  • There are no more controllers and directives in AngularJS. Previously, a controller was assigned to a DOM node, while a directive converted a template into a component-like architecture. However, it is very hard to scale and debug large AngularJS 1.x applications due to the misuse of controllers and/or issues with conflicting directives. In Angular, there is only a single concept—that of a component, which eventually has a selector corresponding to an HTML template and a class containing functions.
  • The $scope object no longer exists in Angular because all properties are now defined inside a component. This is actually good news because debugging errors in $scope (especially with nested scenarios) is very difficult in AngularJS 1.x.
  • Finally, Angular offers better performance and supports both ES5 and ES6 standards. You could write Angular in TypeScript, Dart, or just pure JavaScript.

In this chapter, you will work through several HelloWorld examples to Bootstrap your Ionic app. This process will give you a basic skeleton with which you can start building more comprehensive apps. The majority of apps have similar user experiences flow, such as tabs and side menus.


Setting up a development environment

Before you create your first app, your environment must have the required components ready. These components ensure a smooth development, build, and test process. The default Ionic project folder is based on Cordova's. Therefore, you need the Ionic CLI to automatically add the correct platform (that is, iOS, Android, or Windows phone) and build the project. This will ensure all Cordova plugins are included properly. The tool has many options to run your app in the browser or simulator with live reload.

Getting ready

You need to install Ionic and its dependencies to get started. Ionic itself is just a collection of CSS styles, Angular components, and standard Cordova plugins. It's also a command-line tool to help manage all technologies, such as Cordova. The installation process will give you a command line to generate the initial code and build the app.

Ionic uses npm as the installer, which is included when installing Node.js. Please install the latest version of Node.js from

You will need to install cordova, ios-sim (an iOS Simulator) and ionic:

$ npm install -g cordova ionic ios-sim

You can install all three components with this single command line instead of issuing three command lines separately. The -g parameter is to install the package globally (not just in the current directory).

For Linux and Mac, you may need to use the sudo command to allow system access, as shown:

$ sudo npm install -g cordova ionic ios-sim

The following are a few common options for an integrated development environment (IDE):

  • Xcode for iOS
  • Android Studio for Android
  • Microsoft Visual Studio Code (VS Code)
  • JetBrains' WebStorm
  • Sublime Text ( for web development

All of these have a free license. You could code directly in Xcode or Android Studio, but those are somewhat heavy-duty for web apps, especially when you have a lot of windows open and just need something simple to code. Sublime Text is free for non-commercial developers, but you have to purchase a license if you are a commercial developer. Most frontend developers would prefer to use Sublime Text for coding HTML and JavaScript, because it's very lightweight and comes with a well-supported developer community. Sublime Text has been around for a long time and is very user-friendly. However, there are many features in Ionic that make Visual Studio Code very compelling. For example, it has the look and feel of a full IDE without being bulky. You could debug JavaScript directly inside VS Code, as well as getting autocomplete (for example, IntelliSense). The following instructions cover both Sublime Text and VS Code, although the rest of this book will use VS Code.

How to do it...

VS Code works on Mac, Windows, and Linux. Here are the instructions:

  1. Visit
  2. Download and install for your specific OS
  3. Unzip the downloaded file
  4. Drag the .app file into the Applications folder and drag it to Mac's Dock
  5. Open Microsoft Visual Studio Code
  6. Press Ctrl + Shift + p to open the command palette
  7. Type the shell command in the command palette
  8. Click on the shell command: Install code command in PATH command to install the script to add Visual Studio Code in your terminal $PATH
  9. Restart Visual Studio Code for this to take effect

Later on, you can just write code (including the dot) directly from the Ionic project folder and VS Code will automatically open that folder as a project.

Note that the following screenshots were taken from a Mac:

  1. If you decide to use Sublime Text, you will need Package Control (, which is similar to a Plugin Manager. Since Ionic uses Sass, it's optional to install the Sass Syntax Highlighting package.
  2. Navigate to Sublime Text | Preferences | Package Control.
  1. Go to Package Control: Install Package. You could also just type the partial command (that is, inst) and it will automatically select the right option:
  1. Type Sass and the search results will show one option for TextMate & Sublime Text. Select that item to install:

There's more...


Creating a HelloWorld app via the CLI

The quickest way to start your app is using the existing templates. Ionic gives you some standard out-of-the-box templates via the command line:

  • Blank: This is a simple page with minimal JavaScript code
  • Tabs: These are multiple pages with routes. A route URL goes to a tab
  • Side menu: This is a template with a left/right menu with the center content area
  • Super: This is a template with prebuilt pages and providers, which emphasize the best practices for Ionic app development

How to do it...

  1. To set up the app with a blank template from ionic, use this command:
$ ionic start HelloWorld_Blank blank
  1. If you replace blank with tabs, it will create a tabs template, as shown:
$ ionic start HelloWorld_Tabs tabs
  1. Similarly, the following command will create an app with a sidemenu:
$ ionic start HelloWorld_Sidemenu sidemenu

4. Likewise, the following command will create an app with the super template:

$ ionic start HelloWorld_Super super

Additional guidance for the Ionic CLI is available on the GitHub page:

How it works...

This chapter will show you how to quickly start your code base and visualize the result. More details about Angular and its template syntax will be discussed in various chapters of this book, however, the core concepts are as follows:

  • Component: Angular is very modular because you could write your code in a file and use an export class to turn it into a component. If you are familiar with AngularJS 1.x, this is similar to a controller and how it binds with a DOM node. A component will have its own private and public properties and methods (that is, functions). To tell whether a class is an Angular component or not, you have to use the @Component decorator. This is another new concept in TypeScript since you could enforce characteristics (metadata) on any class so that they behave in a certain way.
  • Template: A template is an HTML string or a separate .html file that tells AngularJS how to render a component. This concept is very similar to any other frontend and backend framework. However, Angular has its own syntax to allow simple logic on the DOM, such as repeat rendering (*ngFor), event binding (click), or custom tags (<my-tag>).
  • Directive: This allows you to manipulate the DOM, since the directive is bound to a DOM object. So, *ngFor and *ngIf would be examples of directives because they alter the behavior of that DOM.
  • Service: This refers to the abstraction to manage models or collections of complex logic besides get/set required. There is no service decorator, as with a component. So, any class could be a service.
  • Pipe: This is mainly used to process an expression in the template and return some data (that is, rounding numbers and adding currency) using the {{ expression | filter }} format. For example, {{amount | currency}} will return $100 if the amount variable is 100.

Ionic automatically creates a project folder structure that looks as follows:

You will spend most of your time in the /src folder because that's where your application components will be placed. This is very different from Ionic 1.x because the /www folder here is actually compiled by TypeScript. If you build the app for iOS, the Ionic build command line will also create another copy at /platforms/ios/www, which is specifically for Cordova to point to. Another interesting change in Angular is that your app has a root component, which is located at /src/app folder, and all other pages or screens are in /src/pages. Since Angular is component based, each component will come with HTML, CSS, and JS. If you add in more JavaScript modules, you can put them in the /src/assets folder, or a better practice is to use npm install so that it's automatically added in the /node_modules folder. Ionic has completely gotten rid of Grunt and Bower. Everything is simplified into just package.json, where your third-party dependencies will be listed.

There is no need to modify the /platforms or /plugins folder manually unless troubleshooting needs to be done. Otherwise, the Ionic or Cordova CLI will automate the content of these folders.

By default, from the Ionic template, the Angular app name is called MyApp. You will see something like this in app/app.component.ts, which is the root component file for the entire app:

This root component of your app and all content will be injected inside <ion-app></ion-app> of index.html.

Note that if you double-click on the index.html file to open it in the browser, it will show a blank page. This doesn't mean that the app isn't working. The reason for this is that the Angular component of Ionic dynamically loads all the .js files and this behavior requires server access via the http:// protocol. If you open a file locally, the browser automatically treats it as a file protocol (file://), and therefore Angular will not have the ability to load additional .js modules to run the app properly. There are several methods of running the app, which will be discussed later.


Creating a HelloWorld app via Ionic Creator

Another way to start your app code base is to use Ionic Creator. This is a great interface builder to accelerate your app development with the drag and drop style. You can quickly take the existing components and position them to visualize how it should look in the app via a web-based interface. Most common components, such as buttons, images, and checkboxes are available.

Ionic Creator allows the user to export everything as a project with all .html, .css, and .js files. You should be able to edit content in the /app folder to build on top of the interface.

Getting ready

How to do it...

  1. Create a new project called myApp:
  1. Validate, to ensure that you see the following screen:
  1. The center area is your app interface. The left side gives you a list of pages. Each page is a single route. You also have access to a number of UI components that you would normally have to code by hand in an HTML file. The panel on the right shows the properties of any selected component.
  2. You're free to do whatever you need to do here by dropping components to the center screen. If you need to create a new page, you have to click on the Add Page in the Pages panel. Each page is represented as a link, which is basically a route in Angular UI-Router's definition. To navigate to another page (for example, after clicking a button), you can just change the link property and point to that page.
  3. There is an edit button on top, where you can toggle back and forth between the edit mode and preview mode. It's very useful to see how your app will look and behave.
  4. Once completed, click the export button at the top of the navigation bar. You have the following four options:
    • Use the Ionic CLI tool to get the code
    • Download the project as a ZIP file
    • Export it to native code (similar to PhoneGap Build), as shown:
    • Export it to the preview mode using the Creator app

The best way to learn Ionic Creator is to play with it.

There's more...

To switch to the preview mode, where you can see the UI in a device simulator, click on the switch button in the top right to enable Test, as illustrated:

In this mode, you should be able to interact with the components in the web browser as if they're actually deployed on the device.

If you break something, it's very simple to start a new project. It's a great tool to use for prototyping and to get the initial template or project scaffolding. You should continue coding in your regular IDE for the rest of the app. Ionic Creator doesn't do everything for you yet. For example, if you want to access specific Cordova plugin features, you have to write that code separately.

Also, if you want to tweak the interface outside of what is allowed within Ionic Creator, it will also require specific modifications to the .html and .css files.


Viewing the app using your web browser

In order to run the web app, you need to turn your /www folder into a web server. Again, there are many methods to do this and people tend to stick with one or two ways to keep things simple. A few other options are unreliable, such as Sublime Text's live watch package or a static page generator (for example, the Jekyll and Middleman apps). They are slow to detect changes and may freeze your IDE, so won't be mentioned here.

Getting ready

The recommended method is to use the Ionic serve command line. It basically launches an HTTP server so that you can open your app in a desktop browser.

How to do it...

  1. First, you need to be in the project folder. Let's assume that it is the side menu HelloWorld:
$ cd HelloWorld_Sidemenu
  1. From there, just issue the simple command line, as shown:
$ ionic serve

That's it! There's no need to go into the /www folder or figure out which port to use. The command line will provide the following options while the web server is running:

The most common option to use here is Ctrl + C to quit when you are done.

There are additional steps to view the app with the correct device resolution:

  1. Install Google Chrome if it's not already on your computer.
  2. Open the link (for example, http://localhost:8100/) from Ionic serve in
    Google Chrome.
  3. Turn on Developer Tools. For example, in Mac's Google Chrome, navigate to View | Developer | DeveloperTools:
  4. Click on the small mobile icon in the Chrome Developer Tools area, as illustrated:
  1. There will be a long list of devices to pick from, as shown:
  2. After selecting a device, you need to refresh the page to ensure that the UI is updated. Chrome should give you the exact view resolution of the device.

Most developers would prefer to use this method to code, as you can debug the app using Chrome Developer Tools. It works exactly like any other web application. You can create breakpoints or output variables to the console.

How it works...

Note that Ionic serve is actually watching everything under the /src folder and transpiring the TypeScript code into JavaScript under /www on the fly. This makes sense because there is no need for the system to scan through every single file when the probability of it changing is very small.

While the web server is running, you can go back to the IDE and continue coding. For example, let's open page1.html or any other template file and change the first line to this:

<ion-view view-title="Updated Playlists">

Go back to the web browser where Ionic opened the new page; the app interface will change the title bar right away without requiring you to refresh the browser. This is a very nice feature when there is a lot of back and forth between code changes and instantly checking how it works or looks in the app.


Viewing the app using the Ionic CLI

So far, you have been testing the web app portion of Ionic. Most of the time, you will need to actually run the app on a physical device or at least an emulator to see how the app behaves and whether all native features work.

Getting Ready

You will need to have the emulator installed. iOS emulator comes when you do npm install, -g ios-sim, and the Android emulator comes with Android Studio. To test the app on a physical device, you must connect the device to your computer via a USB connection.

How to do it...

  1. Add the specific platform (such as iOS) and build the app using the following command line:
$ ionic cordova platform add ios
$ ionic cordova build ios
  1. Note that you need to add the platforms to build the app. However, if you use the standard template from the Ionic CLI, it should already have the iOS platform included. To build and run for Android, you can replace iOS with Android.
  2. To emulate the app using the ios emulator, use the following command line:
$ ionic cordova emulate ios
  1. To run the app on the actual physical iPhone device, use the command line as shown:
$ ionic cordova run ios --device

Viewing the app using Xcode for iOS

You could run the app using Xcode (in Mac) as well.

How to do it...

  1. Go to the /platforms/ios folder.
  2. Look for the folder with .xcodeproj and open it in Xcode.
  3. Click on the iOS device icon and select your choice of iOS simulator:
  4. Click on the run button and you should be able to see the app running in
    the simulator.

There's more...

You can connect a physical device via a USB port and it will show up in the iOS Device list for you to pick it. Then, you can deploy the app directly on your device. Note that iOS Developer membership is required for this. This method is more complex than just viewing the app via a web browser.

However, it's a must when you want to test out your code regarding device features, such as cameras or maps. If you change the code in the /src folder and want to run it again in Xcode, you have to do Ionic Cordova build ios first, because the running code is in the Staging folder of your Xcode project, as illustrated:

For debugging, the Xcode console can output JavaScript logs as well. However, you could use the more advanced features of Safari's Web Inspector (which is similar to Google Chrome's Developer Tools) to debug your app. Note that only Safari can debug a web app running on a connected physical iOS device because Chrome does not support this on a Mac. It's easy to enable this capability, and it can be done with the following steps:

  1. Allow remote debugging for an iOS device by navigating to Settings | Safari | Advanced and enabling Web Inspector:
  2. Connect the physical iOS device to your Mac via USB and run the app
  3. Open the Safari browser
  4. Select Develop | your device's name or iOS Simulator | index.html, as shown:

If you don't see the Develop menu in Safari, you need to navigate to Preferences |Advanced and check on Show Develop menu in menu bar.

Safari will open a new console just for that specific device, just as it's running within the computer's Safari.


Viewing the app using Genymotion for Android

While it's possible to install the Google Android simulator, many developers have an inconsistent experience on a Mac. There are many commercial and free alternatives that offer more convenience and a wide range of device support. Genymotion provides some unique advantages, such as allowing users to switch the Android model and version, supporting networking from within the app, and allowing SD card simulation.

In this section, you will learn how to set up an Android developer environment (on a Mac in this case) first. Then, you will install and configure Genymotion for mobile app development.

How to do it...

  1. The first step is to set up the Android environment properly for development. Download and install Android Studio from
  2. You might be asked to install other libraries if your machine doesn't have the correct dependencies. If that is the case, you should run sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6 from the command line to install them.
  3. Run Android Studio.
  1. You need to install all of the required packages, such as Android SDK. Just click Next twice on the setup wizard screen and click on the Finish button to start the packages' installation.
  2. After the installation is complete, you need to install additional packages and other SDK versions. On the Quick Start screen, select Configure:
  1. After this, select SDKManager, as shown:
  1. It's good practice to install the previous version, such as Android5.0.1 and 5.1.1. You may also want to install all Tools and Extras for later use:
  1. Click on the Install packages... button.
  2. Check the box on Accept License and select Install.
  1. The SDK Manager will give you an SDK path on the top. Make a copy of this path because you need to modify the environment path.
  2. Go to the terminal and type the following command:
$ touch ~/.bash_profile; open ~/.bash_profile
  1. This will open a text editor to edit your bash profile file. Insert the following
    the line, where /YOUR_PATH_TO/android-sdk should be the SDK Path that you
    copied earlier:
export ANDROID_HOME=/YOUR_PATH_TO/android-sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
  1. Save and close that text editor.
  2. Go back to the terminal and type:
$ source ~/.bash_profile
  1. You should see the output as your SDK path. This verifies that you have correctly configured the Android developer environment.
  2. The next step is to install and configure Genymotion. Download and install Genymotion and Genymotion Shell from sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6.
  3. Run Genymotion.
  4. Click on the Add button to start adding a new Android device, as illustrated:
  1. Select the device that you want to simulate. In this case, let's select Samsung Galaxy S5, as follows:
  2. You will see the device being added to your virtual devices. Click on that device.
  3. Then click on Start.
  4. The simulator will take a few seconds to start and will show another window. This is just a blank simulator without your app running inside it yet.
  5. Run Genymotion Shell.
  1. From Genymotion Shell, you need to get a device list and keep the IP address of the device attached, which is the Samsung Galaxy S5. Type devices list.
  2. Type adb connect (or whatever the IP address was that you saw earlier from the devices list command line).
  3. Type adb devices to confirm that it is connected.
  4. Type Ionic Cordova platform adds Android to add Android as a platform for your app.
  5. Finally, type Ionic Cordova run android.
  6. You should be able to see the Genymotion window showing your app.

Although there are many steps to take to get this working, it's a lot less likely that you have to go through the same process over. Once your environment is set up, all you need to do is to leave Genymotion running, while writing code. If there is a need to test the app on different Android devices, it's easy to add another virtual device in Genymotion and connect to it.


Viewing the app using Ionic View

Ionic View is an app viewer that you can download from the App Store or Google Play. When you are in the development process and the app is not complete, you don't want to submit it to either Apple or Google right away but limit access to your testers. Ionic View can help load your own app inside Ionic View and make it behave like a real app with some access to native device features. Additionally, Ionic View lets you use your app on an iOS device without any certification requirements.

Since Ionic View uses the Cordova InAppBrowser plugin to launch your app, all the device features have to be hacked to make it work. Currently, Ionic View only supports SQLite, battery, camera, device motion, device orientation, dialog/notification, geolocation, globalization, network information, vibration, keyboard, status bar, barcode scanner, and zip. It's a good idea to check the updated support list prior to using Ionic View to ensure that your app works properly.

How to do it...

There are two ways to use Ionic View. You can either upload your own app or load someone else's app ID. If you test your own app, follow these steps:

  1. Download Ionic View from either the App Store or Google Play.
  1. Make sure to register an account on
  2. Go to your app's project folder.
  3. Search for the Ionic upload.
  4. Enter your credentials.
  5. The CLI will upload the entire app and give you the app ID, which is 152909f7 in this case. You may want to keep this app ID to share with other testers later.
  6. Open the Ionic View app on the mobile device and log in if you haven't done so already.
  7. Now, you should be able to see the app name on your MY APPS page. Go ahead and select the app name (myApp in this case), as illustrated:
  1. Select VIEW APP to run the app, as shown:
  1. You will see that the app interface appears with initial instructions on how to exit the app. Since your app will cover the full screen of Ionic View, you need to swipe down using three fingers, as illustrated, to exit back to Ionic View:

If there is no code update, the process is the same, except that you need to select SYNC TO LATEST from the menu.

There's more...

To summarize, there are several benefits of using Ionic View, some of which are as follows:

  • It's convenient because there is only one command line to push the app
  • Anyone can access your app by entering the app ID
  • There is no need to have iOS Developer membership to start developing with Ionic. Apple has its own TestFlight app, which is very similar
  • You can maintain an agile development process by having testers test the app as you develop it
  • Ionic View supports a wide range of device features, and that support continues to grow
About the Authors
  • Indermohan Singh

    Indermohan Singh is a Mobile App Developer working in Vienna, Austria, originally from Ludhiana, Punjab. For the past 3 years, he has worked on Angular, Ionic, and TypeScript most of the time. He authored Ionic 2 Blueprint for Packt Publishing, and this is his second book on the subject. Before starting the full-time job, he was freelancer with many startups. During his time as a freelancer, he also mentored learners at, where he was mostly teaching JavaScript. He is also hobbyist musician and loves to create Indian Compositions and play them on harmonium.

    Browse publications by this author
  • Hoc Phan

    Hoc Phan is a technologist with experience in frontend development, cloud computing, and big data. He started programming at the age of 12. Hoc has worked on many JavaScript projects by learning from various online sources and was one of the first few developers who tested Ionic for its feasibility as a JavaScript replacement of the native language of a device. He authored the Ionic Cookbook.

    He frequently speaks at local meetups and cloud computing/big data industry events and conferences. He holds an MBA degree from the University of Washington's Michael G. Foster School of Business.

    Browse publications by this author
Ionic Cookbook -Third Edition
Unlock this book and the full library FREE for 7 days
Start now