Angular 2 Ionic 2 Tutorial

Angular 2 ionic 2 tutorial will guide you to create an hybrid app for mobile using the power of angular 2 and ionic 2.

angular 2 ionic 2
angular 2 ionic 2

With angular 2 ionic 2 we can create apps that run on different mobile operating systems like Android, Windows and IOS.

  • Before we start it’s necessary to install NodeJS, so if you are new please follow this link to install NodeJS :

http://www.angulartypescript.com/angular-typescript-npm/

  • Create a folder and call it : angular2ionic2
environment install
environment install

Download the Android Studio from here:

Download the Android Studio

Hint: we need the Java Development Kit (JDK)

Install Android Studio.

Android Studio contains the Visual studio and the Android SDK.

  • Windows (add sdk to the environment variables):

set ANDROID_HOME=C:\installation folder\sdk

set PATH=%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools

  • Mac

export ANDROID_HOME=/installation folder/sdkexport

PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

If you want to build an iOS app you need an iMac or Macbook. If you don’t have you can use Phonegap from adobe: Phonegap Or Appbuilder Appbuilder

They are cloud based builder.

 We  install cordova with g option (globally):


npm install -g cordova

Discover Angular 2 and Typescript from here.

Start the project
Start the project

We want to build and app that searchs videos from YouTube and allows us to play the selected video.

angular 2 ionic 2 project structure
angular 2 ionic 2 project structure

Open a command line (terminal) and enter to your workspace folder.

angular2ionic2


cd angular2ionic2

  • Install ionic 2 :
     npm install -g ionic@beta 

This will install ionic 2 on your computer.

Now let’s create our angular 2 ionic 2 app, we can right now use the command ionic. (Already installed with the previous command)

 ionic start angular2ionic2 blank --v2 --ts 

Now you should find a folder created for you with the name of: angular2ionic2

All the needed files to start your angular 2 ionic 2 mobile app are installed.

We want to use Typescript as a programming language with Angular 2 ionic 2 app for this reason we add the flag – – ts .

The – – v2 will tell ionic to configure app to use ionic 2.

Our Angular 2 ionic 2 app is ready for development.

And you will get a report at the end of installation.

write the code
write the code

We want to create an app to search a video from YouTube and then when we click on a video from homepage list we navigate to another page to play the video.

Open your editor to edit and start developing your angular 2 ionic 2 mobile app

app Contain all your code source used to develop the app, (HTML pages, .ts files)
hooks Contains the scripts used by the Cordova build process. If needed customize here during building the packages.
node_modules We use npm to manage modules; all modules are stored in this location.
plugins The Cordova plugins stored here.
resources Contains the icon and images for the different platforms.
typings Type definition files for external modules (modules that are written in other script languages and not in TypeScript).
www Contains the index.html.
config.xml The Cordova configuration file (Used when creating the packages).
package.json Contains the list of all npm packages.
tsconfig.json TypeScript compiler configuration file.

The next step. Our first angular 2 ionic 2 app is pretty easy and simple : )

Our APP: We click on a button and we get some data from a WebService then we show the content in our app home page.

 webservice angular 2 ionic 2 typescript
webservice angular 2 ionic 2 typescript
  • We create our service ts: get some data from YouTube web service.
/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';

@Injectable()
export class Angular2YoutubeAppService {

    constructor(private http: Http) {
    }

    getVideos(myQuery) {

        let stringParamsYoutube= "?key=YourKey&type=video&q="+myQuery+"&part=id,snippet";

        let repos = this.http.get(`https://www.googleapis.com/youtube/v3/search`+stringParamsYoutube);

        console.log(repos);

        return repos;
    }

}

As you may notice we decorate our class with @Injectable to make it a service. We will use the Http service from ‘angular2/http’ to bring data from our Online WebService.

angular 2 ionic 2 homepage
angular 2 ionic 2 homepage

 

We suppose you are familiar with angular 2 and typescript. If not please check our tutorial.

  • Open html in home folder. (this folder contains 3 files)
  • html contains the template used for our app.
  • We create a Page that will be used to show the data we receive from the WebService.

home.html

<ion-navbar primary *navbar >
  <ion-title>
    Angular2 Ionic Youtube
  </ion-title>
</ion-navbar>

<ion-content class="home">
  <ion-list inset>
    <ion-item>
      <ion-input  [(ngModel)]="myQuery" type="text" placeholder="Search Youtube"></ion-input>
    </ion-item>
  </ion-list>
  <div padding>
    <button light block (click)="getVideos()">Search</button>
  </div>
  <ion-card *ngFor="#video of myVideos" (click)="playVideo(video)">
    <ion-card-header light>
      {{video.snippet.title}}
    </ion-card-header>
    <ion-card-content>
      <img src="{{video.snippet.thumbnails.high.url}}">
    </ion-card-content>
  </ion-card>
</ion-content>
  • Inside home folder open the file ts to write the Angular 2 ionic 2 Typescript code.
  • To create a component ionic uses another decorator to replace the @Component. Ionic uses @Page
  • In our ts we will subscribe to our Observable! Yes observable, as you know Http service in Angular 2 uses Observables to asynch.

You want to read about RxJS Observables in Angular 2 ?

home.ts

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Page, NavController} from 'ionic-angular';
import {Angular2YoutubeAppService} from "../../services/angular2yotubeapp";
import {PlayVideoPage} from "../play-video/play-video";

@Page({
  templateUrl: 'build/pages/home/home.html',
  providers: [Angular2YoutubeAppService]
})
export class HomePage {

  public myVideos;
  public myQuery;
  constructor(private videosService: Angular2YoutubeAppService,
              private nav: NavController) {
  }
    // get video from youtube with the current query
    getVideos() {
            this.videosService.getVideos(this.myQuery).subscribe(
                data => {
                  let myData=data.json();
                  this.myVideos =  myData.items;
                  console.log( this.myVideos );
                },
                err => console.error(err),
                () => console.log('Youtube search completed')
            );
    }

    playVideo(video) {
        //go to play-video.html and send the video variable (the selected video)
        this.nav.push(PlayVideoPage, { video: video });
    }

}
  • You have noticed new kind of element <ion- this is ionic tag style.
ionic 2 navigation
ionic 2 navigation

First open the file app/app.ts

You can notice this portion of code :

<ion-nav [root]="rootPage"></ion-nav>

Explanation:

  • Now we have one page that contains the list of videos.
  • We want to navigate: from home page to play page.
  • We will add a folder play-video and add two files play-video.html and play-video.ts.
  • Play-video.ts will call the service to get the videos.
  • In play-video.html we will play the selected video (from home page).
angular 2 ionic 2 navigation
angular 2 ionic 2 navigation

play-video.html

<ion-navbar *navbar>
    <ion-title>
        {{video.snippet.title}}
    </ion-title>
</ion-navbar>

<ion-content>

    <div class="image-left embed-video">
        <div class="videoWrapper">
            <iframe width="560" height="315" src="https://www.youtube.com/embed/{{video.id.videoId}}?rel=0" frameborder="0" allowfullscreen></iframe>
        </div>
        <p>
            {{video.snippet.description}}
        </p>
    </div>
</ion-content>
We embed the YouTube player.

now we write the play-video.ts

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Page, NavController, NavParams} from 'ionic-angular';

@Page({
    templateUrl: 'build/pages/play-video/play-video.html',
 })
export class PlayVideoPage {
    public video;

    constructor(private nav: NavController, private navParams: NavParams) {
        //when we navigate from the homepage to this page
        //we send the clicked video, and here we get it
        //using the NavParams : ) now we have our video
        //we can show the details we want, we will need the title and videoId (id)
        this.video = navParams.get('video');

    }
}
We call the YouTube web service to retrieve the videos corresponding to our query.
angular 2 ionic 2 emulate
angular 2 ionic 2 emulate

To view (run) your angular 2 ionic mobile app in a like Mobile environment (Andoird, IOs ) run the ionic serve with the option ( – l ) or (-lab)

ionic serve -l

Click enter and a window will appear under:

http://localhost:8100/ionic-lab

angular 2 ionic 2 play
angular 2 ionic 2 play

You want to build the apk file to publish it on play store?

Or maybe you want to install your app on your devices?

all files from here:angular-2-ionic-2-app

Our example uses typescript as programming language.