Getting started with Ionic 2
Since Angular 2 became final, the final version of Ionic 2 comes in sight, which is heavily based on Angular 2. And yes, Ionic announced its first Release Candidate for version 2! This post will introduce you to version 2 of the Ionic framework, and help you setting up a simple App.
What is Ionic
“Ionic is an HTML5 mobile app development framework targeted at building hybrid mobile apps. Hybrid apps are essentially small websites running in a browser shell in an app that have access to the native platform layer.
Unlike a responsive framework, Ionic comes with very native-styled mobile UI elements and layouts that you’d get with a native SDK on iOS or Android but didn’t really exist before on the web. Ionic also gives you some opinionated but powerful ways to build mobile applications that eclipse existing HTML5 development frameworks.”
from: ionicframework.com.
Why Ionic
So there’re already several frameworks out there that seems to do the job. We have Angular as a proper front-end JavaScript framework and Cordova to build hybrid apps in HTML5. Shortly, Ionic combines these two and adds some native look and feel to it. So when you want more than just running your web app in a mobile browser, try Ionic. To see it in perspective, this is how it comes together:
Preparation
Before we can use Ionic, we need to install Ionic CLI, npm and Cordova. Follow the instructions on Ionic’s documentation page to install Ionic and its dependencies.
As IDE I recommend using Visual Studio Code. It is free of charge, runs on OSX/Windows/Linux and supports JavaScript, TypeScript, HTML, CSS, and more out of the box. But you can use any other IDE or (text) editor if you prefer. Now you’ve installed the necessary software we can create the App. Open a command prompt or Terminal and run the command:
ionic start MyFirstApp blank --v2
This will pull down Ionic 2, install npm modules for the application, and get Cordova set up and ready to go. We pass ‘blank’ as argument to start with an empty project. It’s also possible to create an App that already contains a sidemenu, tab buttons or based on an existing project, see the CLI documentation.
Now start the app with the following two commands:
cd MyFirstApp
ionic serve
When finished it will open a browser and load the App. You will see the default homepage saying: “The world is your oyster”.
Change the homepage
The folder MyFirstApp contains a minimal working Ionic 2 project. For now the most important part is the src/ folder. The src/ folder contains the raw, uncompiled code. When we run ionic serve, the TypeScript code is transpiled into JavaScript and the SASS files into one CSS file. The src/ folder looks like this:
src/
app/
assets/
pages/
home/
home.html
home.scss
home.ts
theme/
index.html
We will focus on the folder src/pages/home/. Start Visual Studio Code and open the folder MyFirstApp. Now open home.html and see:
Ionic Blank
The world is your oyster.
If you get lost, the docs will be your guide.
Replace everything inside <ion-content> tags with Hello world. When you save, you’ll see in the Terminal something has changed, and the app in the browser will be refreshed and now shows the text ‘Hello world.
Display a list of items
We will create a page that shows a list of commits from Github on the Ionic2 project. We use Github because it has a simple and public available REST API. Before fetching real data from Github, first create the list view.
Open home.ts and add a field member to hold the list of items we’re going to show. So after export class HomePage { add:
commits: Array = ['Commit 1', 'Commit 2'];
Open home.html and replace the body of
{{c}}
Now let’s fetch some real data from Github. The REST endpoint we are going to use is: https://api.github.com/repos/driftyco/ionic/commits. To find out what the result looks like just open this URL in a browser. For more details consult the Github API doc. To fetch data we need to import the Http class of Angular. Open home.ts and add at the first line:
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
These are two imports, the first imports the Http and the second one I will come back to later on. Remove the hardcoded commits, e.g. replace line 11 with: commits: Array<any>;
In the constructor (line 12) add an extra parameter: private http: Http so that the new constructor looks like:
constructor(public navCtrl: NavController, private http: Http) {
This makes http available as member of the HomePage class. When the HomePage is loaded, Angular will call the ngOnInit() method, this is the right moment to implement the HTTP call to Github. So below the constructor, add the following method (e.g. after line 15):
ngOnInit() {
this.http.get('https://api.github.com/repos/driftyco/ionic/commits')
.map(response => response.json())
.subscribe(commits => {
this.commits = commits;
});
}
Let’s take a look, line by line at what we just added. http.get() is performing a GET request to the given URL and its return value is an Observable object. Details about Observables are out of scope for this post. This would make a good topic for a next post though. For now assume that it’s an Object that emits a stream of events, and we can apply functions to that stream. In this example it will emit one event, containing the HTTP Response from Github.
The body of the response contains a JSON string, so first we’ll convert it to a JSON object with the map() function. This is why we added the second import. When you omit this import you’ll get an compile error stating: “Property ‘map’ does not exist on type ‘Observable<Response>’.”.
Finally we listen to the events with subscribe(). The JSON Response is a list of commits, and we choose to directly assign the JSON object to this.commits
When you open the App in the browser you’ll see a list of [Object, Object]. That’s because in home.html we print each element in the list of commits with: {{c}}, and those elements are Objects. Let’s change the markup to show a few details of a commit. Replace {{c}} with:
{{c.commit.committer.name}}
{{c.commit.committer.date}}
{{c.commit.message}}
Now you’ll see the list of commits and the avatar of their author like:
Maybe you notice that the date is not nicely readable, because we directly displayed the value and that is ISO 8601 formatted. To make it better readable we add a Pipe. Pipes are a common way in Angular to write display values. Say that we only want to see the day, month, hours and minutes, we can add the DatePipe: | date:' dd MMM HH:mm'. So the line writing the date value will be:
{{c.commit.committer.date | date:' dd MMM HH:mm'}}
We started with generating a blank Ionic app. And now it displays a list of commits, fetched from Github. The full project of the app we created can be found on Github.
One last command you really need to know is:
ionic serve --lab
This displays multiple platforms next to each other, so that you see Android, iOS and Windows at once.
It comes in handy during development to run the App in a browser. But when you want to make use of native SDK like the camera or GPS, you need to ‘build’ the app for a specific platform. With one command you can ‘build’ the app which can be installed on a real device or in an emulator. How this exactly works is out of scope for this post.
So this was a brief introduction into Ionic 2. When you start working with Ionic 2, you probably want to learn more about the concepts behind Angular 2 and Ionic 2. Also the Ionic website contains tutorials and documentation.