Ionic 2 Cookbook - Second Edition

4.6 (5 reviews total)
By Hoc Phan
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Creating Our First App with Ionic 2

About this book

Developing real-time apps is the need of the hour, and apps that deal with humongous amounts of user data and real-time information that needs to be updated frequently are in high demand. Currently, one of the most popular frameworks for this task is Ionic Framework, which is undergoing a major makeover.

This book will get you started with Ionic and help you create Angular 2 components that interact with templates. From there, you'll 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 the application to make it look pretty.

You'll learn to add in a local push notification in order to test the app. 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 as well as customizing your own. 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:
November 2016
Publisher
Packt
Pages
320
ISBN
9781786465962

 

Chapter 1. Creating Our First App with Ionic 2

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

 

Introduction


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 for 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 in this active 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 discover product and market fit. The best practice is to think of the users first. There are instances where a simple responsive design website is a better 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:

  • It's written on top of AngularJS. Ionic 1.x was based on AngularJS 1.x, while Ionic 2.0 is on top of AngularJS 2.0.

  • 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 2.0. All of these changes are applicable to Ionic 2 as well. Consider the following examples:

  • AngularJS 2.0 utilizes TypeScript, which is a superset of the ECMAScript 6 (ES6) standard, to build your code into JavaScript. This allows the developers to leverage TypeScript features, such as type checking, during the complication step.

  • There will be no more Controllers and Directives in AngularJS. Earlier, 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. Moving to AngularJS 2.0, there is only a single concept of Component, which eventually has a selector corresponding to an HTML template and a class containing functions.

  • The $scope object will no longer exist in AngularJS 2.0 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, AngularJS 2.0 promises to have better performance and supports both ES5 and ES6 standards. You could write AngularJS 2.0 in TypeScript, Dart or just pure JavaScript.

In this chapter, you will go through several HelloWorld examples to Bootstrap your Ionic app. This process will give you a quick skeleton to start building more comprehensive apps. The majority of apps have similar user experience flows, 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 process of development, build and test. 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, AngularJS components, and standard Cordova plugins. It's also a command-line tool to help manage all technologies, such as Cordova and Bower. 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 https://nodejs.org/en/download/.

You will need to install Cordova, ios-sim (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)

  • Sublime Text (http://www.sublimetext.com/) 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 2 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 https://code.visualstudio.com.

  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 command palette.

  7. Type shell command in 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 to take effect.

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

    Note

    Note that the following screenshots are done via Mac.

  11. If you decide to use Sublime Text, you will need Package Control (https://packagecontrol.io/installation), which is similar to a Plugin Manager. Since Ionic uses Sass, it's optional to install the Sass Syntax Highlighting package.

  12. Navigate to Sublime Text | Preferences | Package Control:

  13. Go to Package Control: Install Package. You could also just type the commands partially (that is, inst) and it will automatically select the right option:

  14. Type Sass and the search results will show one option for TextMate & Sublime Text. Select that item to install:

There's More…

There are tons of Sublime Text packages that you may want to use, such as HTML, JSHint, JSLint, Tag, and ColorPicker You can visit https://sublime.wbond.net/browse/popular for additional needs.

 

Creating a HelloWorld app via the CLI


It's quickest to start your app using the existing templates. Ionic gives you the following three 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 center content area.

How to do it…

  1. To set up the app with a blank template from Ionic, use this command:

      $ ionic start HelloWorld_Blank blank --v2
    

    Note

    If you don't have an account in ionic.io, the command line will ask for it. You could either press y or n to continue. It's not mandatory to have an account at this step.

  2. If you replace blank with tabs, it will create a tab template, as shown:

      $ ionic start HelloWorld_Tabs tabs
    
  3. Similarly, the following command will create an app with a side menu:

      $ ionic start HelloWorld_Sidemenu sidemenu --v2
    

The side menu template is the most common template as it provides a very nice routing example with different pages in the /app/pages folder.

Additional guidance for the Ionic CLI is available on the GitHub page, https://github.com/driftyco/ionic-cli.

How it works…

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

  • Component: AngularJS 2.0 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 AngularJS 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, AngularJS 2.0 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 beside 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 would look as follows:

You will spend most of your time in the /app 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 AngularJS 2.0 is that all custom JS and CSS files are placed in the same subfolder or in /app/pages. Since AngularJS 2.0 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 /app folder, or a better practice is to use npm install so that it's automatically added in the /node_modules folder. Ionic 2 completely got 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 inside these folders.

By default, from the Ionic template, the AngularJS app name is called MyApp. You will see something like this in app.js, which is the Bootstrap file for the entire app:

This is acting as the root 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 codebase 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 edit content in the /app folder to build on top of the interface.

Getting ready

Ionic Creator requires registration for a free account at https://creator.ionic.io/ to get started.

How to do it…

  1. Create a new project called myApp:

  2. Validate to ensure that you see the following screen:

    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.

    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 plus sign 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.

    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.

  3. Once completed, click the export button on the top in 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, as follows:

The best way to learn Ionic Creator is to play with it. You can add a new page and pick out any of the existing templates. The following example shows a Login page template:

Here is how it should look out of the box (after export or download):

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 static page generator (for example, the Jekyll and Middleman apps). They are slow to detect changes and may freeze your IDE. So those 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
    
  2. From there, just issue the simple command line, as shown:

      $ ionic serve
    

That's it! There is 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 r to restart or q 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 | Developer Tools.

  4. Click on the small mobile icon in the Chrome Developer Tools area, as illustrated:

  5. There will be a long list of devices to pick from, as shown:

  6. 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 /app folder and transpiling 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 for it to change 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 change and checking on how it works or looks in the app instantly.

 

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 platform add ios
      $ ionic build ios
    

    Note

    Note that you need to do the platform add before building 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 emulate ios
    
  3. To run the app on the actual physical iPhone device, use the command line as shown:

      $ ionic 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. 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 related to device features, such as camera or maps. If you change code in the /app folder and want to again run it in Xcode, you have to do ionic 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 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:

    Note

    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 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 https://developer.android.com/studio/index.html.

    Note

    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.

  2. Run Android Studio.

  3. You need to install all the required packages, such as Android SDK. Just click Next twice at the setup wizard screen and click on the Finish button to start the packages' installation.

  4. After the installation is completed, you need to install additional packages and other SDK versions. On the Quick Start screen, select Configure, as illustrated:

  5. After this, select SDK Manager, as shown:

  6. It's good practice to install the previous version, such as Android 5.0.1 and 5.1.1. You may also want to install all Tools and Extras for later use:

  7. Click on the Install packages… button.

  8. Check the box on Accept License and select Install.

  9. 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.

  10. Go to the terminal and type the following command:

      $ touch ~/.bash_profile; open ~/.bash_profile.
    
  11. This will open a text editor to edit your bash profile file. Insert the following 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
      export PATH=$ANDROID_HOME/tools:$PATH
    
  12. Save and close that text editor.

  13. Go back to terminal and type.

      $ source ~/.bash_profile
      $ echo $ANDROID_HOME
    
  14. You should see the output as your SDK Path. This verifies that you have correctly configured the Android developer environment.

  15. The next step is to install and configure Genymotion. Download and install Genymotion and Genymotion Shell from genymotion.com.

  16. Run Genymotion.

  17. Click on the Add button to start adding a new Android device, as illustrated:

  18. Select a device that you want to simulate. In this case, let select Samsung Galaxy S5, as follows:

  19. You will see the device being added to your virtual devices. Click on that device.

  20. Then click on Start:

  21. 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 yet:

  22. Run Genymotion Shell.

  23. From Genymotion Shell, you need to get a device list and keep the IP address of the device attached, which is Samsung Galaxy S5. Type devices list:

  24. Type adb connect 192.168.56.101 (or whatever the IP address was that you saw earlier from the devices list command line).

  25. Type adb devices to confirm that it is connected.

  26. Type ionic platform add android to add Android as a platform for your app.

  27. Finally, type ionic run android.

  28. You should be able to see the Genymotion window showing your app.

Although there are many steps 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 in 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 completed, 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 certificate requirement.

Since Ionic View uses 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 App Store or Google Play.

  2. Make sure to register an account on ionic.io.

  3. Go to your app's project folder.

  4. Search for ionic upload.

  5. Enter your credentials.

  6. 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.

  7. Open the Ionic View app on the mobile device and log in if you haven't done so already.

  8. 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:

  9. Select VIEW APP to run the app, as shown:

  10. 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 even have iOS developer membership to start developing with Ionic. Apple has its own TestFlight app, in which the use case is very similar

  • You can stay agile in the developer process by having testers test the app as you develop it

  • Ionic View has a wide range of device feature support and continues to grow

About the 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

Latest Reviews

(5 reviews total)
Got me through my initial stages using Ionic 2.
Noch nicht durchgearbeitet, aber... bereits die einleitende Zusammenfassung zu Angular ist vielversprechend. Die ersten Kapitel zum Hauptthema, die ich in Arbeit habe, halten das soweit. Stil des Autors sehr schön verständlich.
Everything was fine. It was a good read