Ionic 2 Tutorial - Building a hybrid mobile app using Angular

Posted by: V Keerti Kotaru , on 3/30/2017, in Category HTML5 & JavaScript
Views: 41997
Abstract: The Ionic framework is one of the most popular hybrid mobile application frameworks. This tutorial focuses on building a simple hybrid app using Ionic 2, Angular 2 and TypeScript.

Mobile has changed the landscape of consumerism. Mobile Apps provide new opportunities for businesses and organizations to connect with their customers.

While these apps provide convenience (with offline features, push notifications etc.) and mobility to the users; it is a challenge to develop apps that target multiple mobile platforms/operating systems. With Android, iOS and Windows Phone being the three major platforms, apps need to cater to atleast these platforms to reach a majority of users.

Organizations developing true native apps for multiple mobile platforms need to invest in a variety of tech stack. For example, iOS development could be done using programming languages like Objective C or Swift, Android with Java, and for Windows Phone, XAML with C# is a popular choice. Wouldn’t it be nice to adopt a solution that allowed for one shared language to be used across multiple platforms?

Hybrid mobile frameworks help solve this problem by providing code reusability between platforms. Hybrid apps are built with web technologies (HTML, CSS, and JavaScript) instead of the device’s native development language.

PhoneGap/Cordova is one such hybrid mobile framework that allows developing an app with familiar tech stack- i.e. JavaScript, HTML and CSS. Apps can tap into native, mobile device features using PhoneGap plug-ins that can act as bridge between the JavaScript platform and the device hardware layer.

Introducing Ionic 2

The Ionic framework, one of the most popular hybrid mobile application frameworks, combines the power of PhoneGap and Angular.

Developers can use ready-made Angular directives, services etc. that eases mobile app development. Mobile device or hardware features like camera, GPS, gyroscope are accessed using PhoneGap plugins. More importantly, Ionic 2 supports Windows Phone platform along with Android and iOS.

This article focuses on Ionic Framework version 2 which uses Angular 2 with TypeScript.

The article also uses Visual Studio Code IDE (VS Code) for ease of development and features. It is a great IDE for AngularJS and TypeScript development and hence is a preferred choice for many while working with the Ionic Framework.

Read the article titled Visual Studio Code Condensed to learn more about VS Code features.

Note: Visual Studio users can take advantage of Tools for Apache Cordova and starter projects. Follow the link for more information and download the content.

Ionic 2 - Pre-requisites and Installation

1. NPM – Node Package Manager needs to be available on the developer machine. Download NodeJS installable from http://nodejs.org

2. Cordova and Ionic – Install Cordova and Ionic globally on the developer machine using NPM

npm install -g cordova ionic

Getting Started with Ionic

Use the following Ionic CLI command to get started with a new Ionic app.

ionic start dinosaur-wiki blank --v2

--v2 indicates generating an Ionic 2 project.

“blank” generates codebase using a basic blank template. Alternatively, we may use tabs (for a mobile UI with tabs) or sidemenu(for navigation to other pages using links on side menu) .

dinosaur-wiki is the name of the new mobile app.

“start” gets you started with a new project. Once the project is created we can continue to use the ionic CLI to add new pages, Angular 2 components, services etc.

Note: Ionic CLI prompts to create an account (for free). In future, it will help connect the app to a profile (on cloud) and many useful features. Logged-in users will not see this prompt.

The above command should generate a new folder named dinosaur-wiki. CD into this new directory and run following command to see the outcome of a basic scaffolded mobile app.

ionic serve

Ensure that the node_modules have been installed. If it’s interrupted during the initial step for any reason, run npm install before running ionic serve.

It now launches the app on the default browser. Ionic / PhoneGap / Cordova apps run on a browser. Chrome developer tools is a good place to start the browser emulator for mobile. Launch the URL (default is localhost:8100) in Google Chrome, open developer tools and click on emulator icon to start emulation. Choose your mobile device from the list.

See figure 1 for details.

chrome-dev-tools

Figure 1 Chrome Developer Tools and Emulator

Notes:

- Ionic serve live reloads the page after each change and saves the changes.

- Refer to “Alternatives for browser testing the app” section in Appendix for other options to emulate an Ionic App.

Hybrid Apps

As described earlier, PhoneGap and Hybrid mobile app development features allow developing applications in one code base and deploying across mobile platforms like Android, iOS and Windows Phone.

PhoneGap achieves this by using a Web View on top of mobile app skeleton. Web View is a browser without bezels like address bar, status bar etc. The HTML, JavaScript and CSS is rendered on it like any other browser. This architecture allows the same mobile app deployed across platforms.

Ionic apps Look & Feel

One of the problems with Phone Gap is user experience and look & feel. Users would like to use apps that have familiar UI paradigm to their mobile platform. The apps developed in HTML, CSS and JavaScript tend to look like a mobile web page. Users may not find controls look similar to the native platform; they may not be positioned like the native mobile platforms.

Ionic Framework and default CSS helps by rendering controls that look similar to native controls. It is done out-of-the-box without writing any additional code for each platform. See figure 2 and figure 3. The app in the picture is generated using Ionic CLI and tabs template.

ionic-winphone-iphone-dialog

Ionic 2 Code Sample

The sample being described in this article shows a list of dinosaurs. Tap on an item to navigate to a detailed view that shows more information about the selected dinosaur. For the sake of simplicity, this article does not retrieve data from an API. It loads JSON object shipped with the app.

 

ionic-app-list-details

Let us start by getting data about dinosaurs. We will represent the data as a list in the UI.

It is a good practice to handle data in a reusable service. It will help cater to multiple components needing dinosaur data. It will also help data access enhancements (like obtaining data from an API) to a single place in the app.

We can create a new Angular service using Ionic CLI. Run the following command. It will help scaffold skeleton code for the service.

ionic g provider data-access

The service class is created under data-access.ts. DataAccess will be the name of the new service. It will be added in a folder named providers.

The option g (for generate) and provider is used to generate an injectable Angular 2 service skeleton.

Import the service in app.module.ts and add to the list or providers in the Angular module.

import { DataAccess } from '../providers/data-access';

@NgModule({
  declarations: [...
  imports: [...
  bootstrap: [IonicApp],
  entryComponents: [...
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, DataAccess]
})
export class AppModule {}

In the service, return some mock dinosaur data. For simplicity, we are retrieving it from a JSON file named dinosaurs.json in data folder.

import { Injectable } from '@angular/core';
import data from '../data/dinosaurs.json';

@Injectable()
export class DataAccess {
  constructor() {}

  getDinosaurs(){
    return data.dinosaurs;
  }
}

HomePage (src/pages/home/home.ts is the first Ionic page that loads as the app is launched. We can load and show dinosaur data here.

Note: To understand the complete call stack to bootstrap the app, refer to section “Ionic app’s bootstrap call flow” in Appendix.

Import the service in the home page and call getDinosarus() to get the JSON array. Set the JSON array on a private field on the class named dinosaurs. It is tied to the list to be rendered in the template.

// For readability removed import statements. Refer to code sample for complete snippet.
export class HomePage {
  private dinosaurs: Array< any > = [];

  constructor(public navCtrl: NavController,
    private dataAccess: DataAccess) {
    this.dinosaurs = this.dataAccess.getDinosaurs();
  }
}

Ionic Template

Use ion-list and ion-item components to render dinosaur data. Iterate through the list using the ngFor directive.

<ion-list>
<ion-item *ngFor="let dino of dinosaurs" text-wrap>
  <ion-thumbnail item-left>
    <img [src]="dino.image">
  </ion-thumbnail>
  <strong>{{dino.name}}</strong>      
  <button ion-button clear item-right (click)="goToDetails(dino)">View</button>
</ion-item>
</ion-list>

Notice ion-thumbnail component and item-left directive. It shows icon/thumbnail aligned to the left on the row. Also, a view button is shown on the right.

As the user clicks on the button, it will navigate to details pages. A handler goToDetails() will be invoked when user clicks the button. Review click handler code below:

goToDetails(dino){
    this.navCtrl.push( DetailsPage, {
      selectedDino: dino
    });
}

Ionic 2 Navigation

Ionic 2 has a different approach to navigation compared to Angular routing or Ionic 2. In Ionic navigation, the controller manages views/pages as a stack. Pages are pushed and popped.

The current page is top most view in the stack.

To navigate to the details screen, the navigation controller (injected in the home page) pushes DetailsPage. It also passes selected dinosaur object as context to the new page.

Create a Details Screen

Let’s now add another page to show dinosaur details. Use the following Ionic CLI command to add a new page.

ionic g page details

Import and add the page to the module (app.module.ts).

import { DetailsPage } from '../pages/details/details';
@NgModule({
  declarations: [
    MyApp,
    HomePage,
    DetailsPage
    ],
  imports: [
    IonicModule.forRoot(MyApp)],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    DetailsPage
    ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, DataAccess]
})
export class AppModule {}

As the page is navigated to, read context from previous page. As we have seen earlier, the home screen passes on selected dinosaur from the list. Details page reads dinosaur object and renders as a card. Review the following code for reading context from navParams:

@Component({
  selector: 'page-details',
  templateUrl: 'details.html'
})
export class DetailsPage {
  dino: Dinosaur

  constructor(public navCtrl: NavController, public navParams: NavParams) {}

  ionViewDidLoad() {
    this.dino = this.navParams.get("selectedDino");
    console.log(this.dino.name);
  }
}

Notice, the class variable dino is of type Dinosaur. Refer to the complete sample for a custom TypeScript interface named Dinosaur.

Template

The following template renders the view for the page. We are using Ionic Card component to showcase dinosaur details.

<ion-card *ngIf="dino">
    <ion-card-header>      
        <strong>{{dino.name}}</strong>      
    </ion-card-header>
    <ion-card-content>
        <div>
            <img />
        </div>
        <div>
            Appeared {{dino.appeared}} years ago 
            and vanished {{dino.vanished}} years ago.
            She was {{dino.height}} ft high and 
            {{dino.length}} ft long. She weighed 
            {{dino.weight}} pounds.
        </div>
    </ion-card-content>
</ion-card>

Conclusion

Ionic framework is a powerful framework for hybrid mobile app development. This Ionic 2 tutorial details the basics for getting started with Ionic 2.

Further, the framework provides rich component API to ease mobile app development. The Ionic Native features encapsulate PhoneGap plugins. It makes it easy to integrate the native device level features with the Hybrid mobile app. Some of these features include accessing camera, gyroscope, location services etc.

Ionic also provides many services on the cloud for easy deployment to devices & testing, push notification, data storage etc. Refer to “Further Reading” section in Appendix for useful links and articles.

Download the entire source code of this article (Github)

Appendix

Ionic app’s bootstrap call flow

Please read through this section to understand bootstrap process. It helps understand folder structure and call-stack while launching the app.

- src/Index.html is the start point for the application. Angular application is contained in this HTML page.

- Index.html loads main.ts (TypeScript file) which bootstraps the Angular application. It is located in src/app. As mentioned earlier, we are using Angular2 and TypeScript for Ionic mobile app development.

- The main.ts loads the module from app.module.ts in the same directory. Angular application is bootstrapped here.

- app.module.ts sets MyApp from app.component.ts as Ionic app’s root.

- MyApp has code to handle details when PhoneGap is ready. This point onwards, PhoneGap plugins could be used. In the sample, it hides splash screen and sets default style to app’s status bar.

Note: Ionic uses PhoneGap plugins for accessing phone’s native hardware features.

- MyApp also sets HomePage as the root. HomePage located at src/pages/home/home.ts

Alternatives for browser testing the app

The article describes using Google Chrome – Developer Tools for browser emulation of the app. Following are two additional options :

1) Responsinator

It is a good tool to verify responsiveness of the UI. In other words, test if an application renders as expected on various mobile and tablet device screen sizes.

Launch the URL, http://www.responsinator.com on any browser. Within the website, provide your application URL. In this case, it is localhost:8100 to browser emulate the Ionic app in landscape and portrait modes on various mobile and tablet screen-sizes.

2) Ripple – Google Chrome Extension

Find and install Ripple from Google Chrome Webstore. Once enabled, it emulates various mobile and tablet device screen sizes. Along with screen size, it can emulate geo location, accelerometer, PhoneGap events like device ready etc.

References and further reading

- Ionic Framework Website – http://ionicframework.com

- Navigation in Ionic 2 - https://www.joshmorony.com/a-simple-guide-to-navigation-in-ionic-2/

- Dinosaur data – https://dinosaur-facts.firebaseio.com/.

- Dinosaur Image Reference - spore.com

- Responsinator for emulation- http://www.responsinator.com

 

Thanks to Mahesh Panhale for technically reviewing this article.

 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
V Keerti Kotaru is an author and a blogger. He has authored two books on Angular and Material Design. He was a Microsoft MVP (2016-2019) and a frequent contributor to the developer community. Subscribe to V Keerti Kotaru's thoughts at his Twitter account. Checkout his past blogs, books and contributions at kvkirthy.github.io/showcase.


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!