ion-spinner Component: Ionic 2

Today lets see how we can use ion-spinner components and the animated SVG(Scalable Vector Graphics) it provides.

Using spinner components we can indicate the user that the data is being loaded in the background. This increases the usability and accessibility of the application and enhances the user experience.

loading image

Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. The SVG specification is an open standard developed by the World Wide Web Consortium (W3C) since 1999. SVG images and their behaviors are defined in XML text files.

Related Read:
setTimeout and setInterval methods: Ionic 2

ion-spinner Component: Ionic 2


[youtube https://www.youtube.com/watch?v=rCwCsEcI3EU]

YouTube Link: https://www.youtube.com/watch?v=rCwCsEcI3EU [Watch the Video In Full Screen.]



src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Data } from '../../providers/data';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  companies: any = 0;
  constructor(public navCtrl: NavController, public data: Data) {
    var temp = this;
  setTimeout(function(){ 
        temp.data.loadAll().then(result => {
            temp.companies =  result;
        });
    }, 3000);
  }
}

Here am using setTimeout method to induce 3 seconds or 3000 milliseconds of delay in assigning return value to the variable companies. Also note that I’ve initialized companies variable to zero.

src/pages/home/home.html

  < ion-spinner name="circles" *ngIf="companies == 0">
  < /ion-spinner>
  < ion-list *ngIf="companies != 0">
    < ion-item *ngFor="let Company of companies">
      {{Company.name}}
    < /ion-item>
  < /ion-list>

So there would be a delay of 3 seconds before the data is being loaded. So till then the value of variable companies will be zero. So we use *ngIf directive to show spinner until the value of companies stays zero. When it’s not zero(after 3 seconds) the list items are being displayed and the ion-spinner is removed from the DOM.

Styling – CSS
You can change the display property of the spinner using CSS styling.

src/pages/home/home.scss

ion-spinner * {
  width: 28px;
  height: 28px;
  stroke: #444;
  fill: #222;
}

stroke is the border property. Fill is background color property.

setTimeout and setInterval methods: Ionic 2

Today lets learn how to use JavaScript’s setTimeout and setInterval methods in our Ionic 2 project(which uses Typescript by default).

Related Read:
Basics of Injectable or Providers: Ionic 2

In this tutorial, I’ll be delaying the display of some list items using setTimeout and setInterval methods of JavaScript and will display the company names(as list items) on the home page.

Using setTimeout and setInterval methods: Ionic 2


[youtube https://www.youtube.com/watch?v=dyXZcS8wIWc]

YouTube Link: https://www.youtube.com/watch?v=dyXZcS8wIWc [Watch the Video In Full Screen.]



src/providers/data.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
 
@Injectable()
export class Data {
data: any;
  constructor(public http: Http) {
    this.data = [
      {name: 'Microsoft', code: 324, product: 'Windows 10'},
      {name: 'Apple', code: 678, product: 'iPhone 7'},
      {name: 'Google', code: 567, product: 'Pixel'},
      {name: 'Oracle', code: 89, product: 'RDBMS'},
      {name: 'IBM', code: 542, product: 'Computer Hardware and Software'}
    ];
  }
 
  loadAll(){
      return Promise.resolve(this.data);
  };
}

Here we have an array with couple of objects, which has company name, unique id/code and product details. We also have defined a method loadAll() which returns this.data array as a promise.

src/pages/home/home.html

 < ion-list>
    < ion-item *ngFor="let Company of companies">
      {{Company.name}}
    < /ion-item>
  < /ion-list>

src/pages/home/home.ts: setInterval

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Data } from '../../providers/data';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  companies: any;
  constructor(public navCtrl: NavController, public data: Data) {
    var temp = this;
    var i = 0;
    setInterval(function(){ alert('count '+(i++));
        temp.data.loadAll().then(result => {
            temp.companies =  result;
        });
    }, 3000);
  }
}

Here we do not use this keyword/variable inside setInterval method, as it would reference to setInterval method and not the HomePage class component. So we take a temporary variable temp outside setInterval method and assign this keyword to it. Now using temp variable we can invoke class component properties and methods.

setinterval method keeps calling itself after every set interval of time. It keeps calling itself until it is stopped using clearInterval() method.

    var temp = this;
    var i = 0;
    var id = setInterval(function(){ alert('count '+(i++));
        temp.data.loadAll().then(result => {
            temp.companies =  result;
        });
    }, 3000);
    clearInterval(id);

Similarly, setTimeout method
src/pages/home/home.ts: setTimeout

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Data } from '../../providers/data';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  companies: any;
  constructor(public navCtrl: NavController, public data: Data) {
    var temp = this;
    var i = 0;
    setTimeout(function(){ 
        temp.data.loadAll().then(result => {
            temp.companies =  result;
        });
    }, 3000);
  }
}

Here setTimeout is executed only once after 3 seconds or 3000 milliseconds. To halt or clear the setTimeout event, we can use clearTimeout() method.

    var temp = this;
    var i = 0;
    var id = setTimeout(function(){ 
        temp.data.loadAll().then(result => {
            temp.companies =  result;
        });
    }, 3000);
   clearTimeout(id);

Note:
Make sure to import the page component and service provider in src/app/app.module.ts file.

Basics of Injectable or Providers: Ionic 2

Today lets learn about the basics of injectables or providers in Ionic 2. Injectable or provider concept is same as factory or services in Ionic 1 and angular 1.

Injectables are kind of an abstract layer between your application and external or internet data service.

Related Read:
Basics of Page Component: Ionic 2

Injectable or Providers: Ionic 2


[youtube https://www.youtube.com/watch?v=f7pCBCECI5M]

YouTube Link: https://www.youtube.com/watch?v=f7pCBCECI5M [Watch the Video In Full Screen.]



Let us first create a provider by using CLI command

ionic g provider Data

g is a short name for generate
Data is our provider name. We can give any name to our provider.

Ionic 2 CLI generates following provider
src/providers/data.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
 
@Injectable()
export class Data {
data: any;
  constructor(public http: Http) {
  }
}

We won’t be using Http and map services in this tutorial. We’ll still retain Http reference as we’ll be using it in our next tutorial i.e., passing data between pages using NavParams class.

src/providers/data.ts Full Source Code

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
 
@Injectable()
export class Data {
data: any;
  constructor(public http: Http) {
    this.data = [
      {name: 'Microsoft', code: 324, product: 'Windows 10'},
      {name: 'Apple', code: 678, product: 'iPhone 7'},
      {name: 'Google', code: 567, product: 'Pixel'},
      {name: 'Oracle', code: 89, product: 'RDBMS'},
      {name: 'IBM', code: 542, product: 'Computer Hardware and Software'}
    ];
  }
 
  loadAll(){
    return Promise.resolve(this.data);
  };
 
}

Here we declare and initiate an array variable( data ) which has couple of objects as its elements. Each object has a company name, a unique code and a product entry. We also define a method called loadAll() which returns the array variable in the form of a promise.

src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Data } from '../../providers/data';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  companies: any;
  constructor(public navCtrl: NavController, public data: Data) {
    this.data.loadAll().then(result => {
      this.companies = result;
    });
  }
}

Here we import the Data provider and then create its instance/reference. Using this reference we call loadAll() method. Since loadAll() method returns a promise, we use then() to capture the result(once the promise is resolved) and then assign the result to a local variable this.companies

src/pages/home/home.html

< ion-header>
  < ion-navbar>
    < ion-title>
      Welcome
    < /ion-title>
  < /ion-navbar>
< /ion-header>
 
< ion-content padding>
  < h2>Company Names< /h2>
  < ion-list>
    < ion-item *ngFor="let Company of companies">
      {{Company.name}} - {{Company.product}}
    < /ion-item>
  < /ion-list>
 
< /ion-content>

Using ngFor directive we iterate through the array and printout the individual company names as a list of items.

Important: Also make sure to import the Data provider inside src/app/app.module.ts file

import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { Data } from '../providers/data';
 
 
@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [Data]
})
export class AppModule {}

Also make sure to specify the class name of the provider(Data) inside providers section.

Output:
Microsoft – Windows 10
Apple – iPhone 7
Google – Pixel
Oracle – RDBMS
IBM – Computer Hardware and Software

Details Arrow: Ionic 2

Today lets see how we can add details arrow or the right arrow icon to our list items in Ionic 2.

ion-item-right-arrow-icon

Ionic uses modes to customize the look of components. Each platform has a default mode, but this can be overridden. For example, an app being viewed on an Android platform will use the md (Material Design) mode. The < ion -app > tag(in index.html) will have class=”md” added to it by default and all of the components will use Material Design styles:

index.html

< ion-app class="md">

Default Modes used on different platforms
ios devices – ios mode.
android devices – md(Material Design) mode.
windows devices – wp mode.

ion-list item Right Arrow Icon: Ionic 2


[youtube https://www.youtube.com/watch?v=gCXS6gRuyvk]

YouTube Link: https://www.youtube.com/watch?v=gCXS6gRuyvk [Watch the Video In Full Screen.]



In ios mode, buttons and anchor elements with ion-item attribute will display right arrow icon by default. If you want to remove this right icon you should add detail-none attribute to your elements.

Note:
1. For removing right arrow icon use detail-none attribute on your elements.
2. To add right arrow icon use detail-push attribute on your elements.

If the arrow still doesn’t display, you need to overriding some variables inside src/theme/variables.scss file.

For iOS Mode: iOS devices

$item-ios-detail-push-show: true;

For md mode: android devices

$item-md-detail-push-show: true;

For wp mode: Windows Devices

$item-wp-detail-push-show: true;

Important:
If you are previewing or testing your ionic 2 application using Chrome browser on Windows machine, then set variable $item-wp-detail-push-show also to true or else simply set the one applicable to your target device.

src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  companies: any;
  constructor(public navCtrl: NavController) {
    this.companies = [
      {name: 'Microsoft', code: 1},
      {name: 'Apple', code: 2},
      {name: 'Google', code: 3},
      {name: 'Oracle', code: 4}
    ];
  }
}

src/pages/home/home.html

  < ion-list no-lines>
    < ion-item *ngFor="let company of companies" detail-push>
      {{company.name}}
    < /ion-item>
  < /ion-list>

For explanation of above code please watch: Basics of Page Component: Ionic 2 video tutorial.

Remove Lines From ion-list items
Add no-lines attribute to ion-list tag to remove the default linings from the list items displayed on the view.

Basic Navigation: Ionic 2

Today lets learn basics of navigation / routing in Ionic 2. Ionic 2 and Angular 2 makes use of navigation stack for its navigation system. i.e., we can push and pop views to and from navigation stack.

Forward Navigation: We push page reference of the page we want to navigate to.
Backward Navigation: We execute pop operation on navigation stack to remove the current view or top view.

Once we push a page reference of the page we want to navigate to, a back button or back arrow symbol is automatically added to the navigation bar and whenever user clicks on it, the pop operation is executed for us automatically.

Basic Navigation or Routing: Ionic 2


[youtube https://www.youtube.com/watch?v=VC-drnHG8Gg]

YouTube Link: https://www.youtube.com/watch?v=VC-drnHG8Gg [Watch the Video In Full Screen.]



Generating Page using Ionic 2 CLI(Command Line Interface)

ionic g page Second

OR

ionic generate page Second

This command creates Second page for us – which will have a TypeScript page(class file or component), a template file and a sass file.

src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SecondPage } from '../second/second';
 
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController) {}
  nextPage(){
    this.navCtrl.push(SecondPage);
  }
}

Here we import the SecondPage page. Next define nextPage method. When nextPage method is invoked, we push reference to the page we want to navigate to, to the NavController reference.

Important: Also make sure to import Second page inside src/app/app.module.ts file and specify the page reference inside declarations and entryComponents section.

src/pages/home/home.html

 < button ion-button (click)="nextPage();">
   Next Page
 < /button>

Here we invoke nextPage method when user clicks on ‘Next Page’ button. This should take the user to the second page. And the user will be presented with a back button in the second page, so that he or she can navigate back to the home page or the first page again – which calls pop method on NavController reference automatically.

Set Root Page

this.navCtrl.setRoot(SecondPage);

using setRoot method, and passing the page reference of the page you want to set as root page, you can set the root page dynamically.

src/pages/second/second.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
 
@Component({
  selector: 'page-second',
  templateUrl: 'second.html'
})
export class SecondPage {
  constructor(public navCtrl: NavController) {
    this.navCtrl.setRoot(SecondPage);
  }
}

Next Video Tutorial
In the next video tutorial we shall learn to pass data between pages while navigating.