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 Link: http://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.

Advertisements

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 Link: http://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 Link: http://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 Link: http://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 Link: http://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.

Remove Element On Click: Ionic 2

This is a basic example wherein we have a list of company names and once the user clicks on individual name, that name gets removed from the list. We’ve not included the http calls and database in this example to keep things simple and minimalistic.

Related Read:
Basics of Page Component: Ionic 2
ngIf, index, first, last: Ionic 2

Remove Element On Click: Ionic 2



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



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: Array< {}>;
  constructor(public navCtrl: NavController) {
    this.companies = [
      {name: 'Microsoft', code: 1},
      {name: 'Apple', code: 2},
      {name: 'Google', code: 3},
      {name: 'Oracle', code: 4},
      {name: 'IBM', code: 5}
    ];
  }
  remove(no){
    (this.companies).splice(no, 1);
  };
}

Here we have an array variable called companies, which has 5 company names in object format. We also have a method called remove which takes 1 parameter. This parameter is the index number of the item being clicked by the user. Once we get this index number we make use of JavaScript’s splice() method and remove the element from the array. Splice takes 2 arguments, the first one being the index(or the position) of the element to be removed and the second argument is the number of elements to be removed from position of the index received.

src/pages/home/home.html

< ion-list no-lines>
  < ion-item *ngFor="let company of companies; 
                     let i = index;" 
             (click)="remove(i);">
     {{company.name}}
  < /ion-item>
< /ion-list>

Here we assign index value to a variable i. We then pass this value of i to remove method once the user clicks on an item. i.e., we pass the index value of the item being clicked by the user, to the remove method.

Real-time Applications
In real-time applications we’ll pass a unique id of the clicked element to the remove method, which is then passed on to some http calls, which removes the item from the database(usually) and if the remove operation is successful we’ll remove the item from the User Interface using JavaScripts Splice() method. And if the remove operation fails, we’ll display appropriate message to the user.

Ionic 2 Video Tutorial List

On this page we’ll list all the Ionic 2 Video Tutorials we produce. You can ask your questions in the comment section of the respective videos when you’ve any doubts related to the tutorial.


ionic-logo

Please support us by sharing this page with your friends on social media sites. Also stay subscribed to our blog and YouTube channel.

Enter your email address:

Ionic is a beautiful, open source front-end SDK for developing hybrid mobile apps with web technologies. Web technologies like angular, HTML5, CSS.

Ionic 2, Free Video Tutorials List

  1. Ionic 2 Starter Templates
  2. Project Structure: Ionic 2
  3. Basics of Page Component: Ionic 2
  4. ngIf, index, first, last: Ionic 2
  5. Remove Element On Click: Ionic 2
  6. Basic Navigation: Ionic 2
  7. Details Arrow: Ionic 2
  8. Basics of Injectable or Providers: Ionic 2
  9. setTimeout and setInterval methods: Ionic 2
  10. ion-spinner Component: Ionic 2
  11. Passing Data Between Pages: Ionic 2
  12. Tappable Attribute: Ionic 2
  13. ngClass Directive: Ionic 2.
  14. Ionic Storage: Ionic 2.
  15. Pull To Refresh: Ionic 2.
  16. List Item Reordering: Ionic 2.
  17. Adding AdMob In Ionic 2
  18. Facebook Banner and Interstitial Ads: Ionic 2
  19. Facebook Native Ads: Ionic 2
  20. Facebook Native Ads Clickable Area: Ionic 2.

..more video tutorials coming soon, stay subscribed.

Ionic 1

  1. Getting Started With IONIC APP
  2. Positioning The Tabs: IONIC APPS
  3. Positioning The Title: IONIC APPS
  4. Ionic grid system
  5. IONIC APP – Open External Links In Mobile Browser
  6. Social Sharing Plugin: Ionic App

ngIf, index, first, last: Ionic 2

Today lets see how we can track the index number of the loop. i.e., the number of completed iterations in a loop. We shall also learn *ngIf conditional operator and its usage.

Related Read:
Basics of Page Component: Ionic 2

*ngIf Conditional Operator
ngIf is called conditional operator because it operates based on conditions i.e., if the conditional statement it has been assigned is true, then the node it is attached to will be rendered or else it’ll not. *ngIf takes boolean values.

Example: If *ngIf is attached to a div and the condition is false, then the div it has been attached to won’t be added to the DOM. If the condition is true, then div is added to the DOM.

ngIf, index, first, last: Ionic 2



YouTube Link: http://www.youtube.com/watch?v=Cb4a-oh_yXM [Watch the Video In Full Screen.]



index, first, last
While we are looping through some array elements inside template file we can know the index of the loop using index variable. We can use ngIf and do something at the first iteration using first variable and similarly we can know the last iteration using last variable.

src/pages/home/home.ts

< ion-list no-lines>
  < ion-item *ngFor="let company of companies; 
                     let i = index; 
                     let lst = last; 
                     let fst = first;">
    {{i+1}}. {{company.name}}  
    <span *ngIf="lst"> - Am last!</span>
    <span *ngIf="fst"> - Am first</span>
  < /ion-item>
< /ion-list>

inside *ngFor we have initiated and assigned index value to variable i, last index value to variable lst and first index value to variable fst.

Inside ion-item we are using *ngIf to check if the iteration is first iteration, if so add ‘Am first’ message besides the first list item i.e., beside Microsoft. We also check if the iteration is a last iteration, if so we display ‘Am last!’ message beside the last item in the list i.e., beside IBM.

Output:
1. Microsoft – Am first
2. Apple
3. Google
4. Oracle
5. IBM – Am last!

Basics of Page Component: Ionic 2

In this video tutorial we shall learn some basics of a page component.

Topics Covered
1. Decorators – little bit
2. Class
3. Template File – ionic list items, For loop in ionic template.
4. Variables in Ionic – data type(number, string, Array, any)
5. Importing libraries and using it in our project.
6. Setting home page of our project.

Related Read:
Project Structure: Ionic 2

Basics of Page Component: Ionic 2



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



In this tutorial we are using a blank template and setting home.html as our home page.

inside src/app/app.component.ts file
We import the HomePage page

import { HomePage } from '../pages/home/home';

next inside the class definition we assign this HomePage as root file for our application

rootPage = HomePage;

Full Source Code src/app/app.component.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
 
import { HomePage } from '../pages/home/home';
 
 
@Component({
  template: `<ion -nav [root]="rootPage"></ion>`
})
export class MyApp {
  rootPage = HomePage;
 
  constructor(platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }
}

Important: Do NOT forget to import all your classes in app.module.ts file, also specify its class name inside declarations and entryComponents section.

src/app/app.module.ts

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

Now lets take a look at our HomePage component, which is present inside pages directory and Home folder
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 {
  constructor(public navCtrl: NavController) {
  }
 
}

Here we have imported two important library files. Component is used to configure the decorator and NavController is used for navigation purposes. In this tutorial we’re not using Navigation, but we’ll make use of it in our next video tutorial.

Decorators
There are 3 types on decorators:
1. Component
2. Pipe
3. Directive

I’ll explain each one of them separately in other videos.

Component
In today’s tutorial we’ve a component and it has a selector and a templateUrl. Selector name is used to inject an element or an attribute into the DOM. TemplateUrl tells the class about its associated template file. Components(Decorative) are placed just above the class definition.

Class
A class is a blueprint of an object. This is where we write our logic. It’ll usually have some properties(public or private or protected) and some methods.

In Ionic 2 class, you might have seen export keyword – which means we can import this file in some other class file and make use of its service or output.

variables
In TypeScript variables are typed – which means, variables have data type.
var1: any; Means variable var1 can take value of any data type.
var1: string; Here var1 can be assigned with string value only.
var1: number; as you might have already guessed, var1 takes number value.
var1: Array< {}>; var1 takes an array as its value.
var1: boolean; var1 takes value true or false.

Wrong initializations
var1: number = ‘Satish’;
var1: string = 1;

Correct initialization
var1: number = 1;
var1: string = ‘Satish’;

src/pages/home.ts

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

Here we have an array called companies – which has a list of company names like Microsoft, Apple, Google, Oracle, IBM. Each of this is stored as an individual element inside the array.

Using ngFor loop we can iterate through this array and display the company names.

*ngFor loop

< p *ngFor="let company of companies">
< /p>

In Ionic 2, we make use of *ngFor for for loop. We declare a new variable company and reference individual elements of the array present inside companies array.

src/pages/home/home.html

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

Here I’m making use of ion-list tag and ion-item tags to display the company names.

ion-list-no-lines

If we want to remove the default lines which come along with the ion-list items then we can add no-lines styling to ion-list tag.

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

In next video tutorial lets learn how to navigate to other pages using Ionic 2 routing.

Project Structure: Ionic 2

Before we move forward with coding, it’s important to know some of the files and folders present inside our ionic 2 project. Since you’re a beginner you might find this video to be confusing and fast paced. But let me assure you, this won’t affect your learning of Ionic 2. How much ever time you spend in understanding the anatomy of an ionic 2 cordova project, you won’t understand it properly until we start coding and utilizing these files and folders for our application needs.

I would advice you to take down whatever you understand in this video in a note-book and keep it for your future reference. It would be handy soon.

anatomy of ionic2 cordova project

hooks: this is not for beginners, so will skip that for now.
node_modules: This is where core libraries like angular2, ionic2, array manipulation, regEx etc are present. We import these libraries in our ionic 2 project and utilize their services.
plugins: Here Ionic 2 project specific cordova plugins are stored. There are many plugins which ionic-native provides which we can make use of for our application needs. For example: If you need to use your devices camera functionality, there is a cordova plugin for that which you can use in your ionic 2 project.
resources: Here we store icon and splashscreen files of our app.
src: is where we can find raw, uncompiled code. Inside src we have our page components(src/pages), application root components(src/app), static files(src/assets) etc, which gets transpiled, compiled, minified and stored inside www folder during the build process. If you edit any file inside www folder, it’ll simply be overwritten during the build process.

Anatomy of an Ionic 2 Project



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



src/assets: We store static resource files in this folder. Example: Image files which we use for our project.

src/pages: For every page you create you’ll add another folder in this directory. For example, if you want to create a login page, you’ll need to create a folder called login(or any other unique name) and then store the login template, login class definition file and login style definition file inside that folder. Ionic CLI can be used to automate this process and I’ll show you how to do it in upcoming video tutorials.

src/theme: This folder has style definition which is applicable for the entire application. We can simply change the value of some variables and customize the look and feel of our application. This will also be explained in a separate video tutorial in coming days.

src/app: This folder is where the ‘root components’ of our application are located. main.dev.ts and main.prod.ts files are responsible for the bootstrapping process of the application. main.dev.ts is active in development mode and main.prod.ts should be used in production environment.

src/app/app.module.ts is the entry point for the app.

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

This essentially controls the work flow of rest of the application.

Using NgModule of angular core library we manage the modules in our ionic 2 applications. All the components and data services we create must be imported in this file and its class name must be specified inside the declarations and entryComponents section. If we have any data service providers we must specify it inside providers block. This file also points to the first component of our Ionic 2 application i.e., MyApp class of src/app/app.component.ts

src/app/app.component.ts is the first component of Ionic 2 application

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
 
import { TabsPage } from '../pages/tabs/tabs';
 
 
@Component({
  template: `<ion -nav [root]="rootPage"></ion>`
})
export class MyApp {
  rootPage = TabsPage;
 
  constructor(platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }
}

This is the first component which gets loaded in our application. It’s simply an empty shell for other components to load into.

One important thing to note here is the rootPage. Since this is a project which uses tabs template, it has automatically assigned the rootPage to the TabsPage present in our src/pages/tabs/tabs.ts page.

src/pages/tabs/tabs.ts component

import { Component } from '@angular/core';
 
import { HomePage } from '../home/home';
import { AboutPage } from '../about/about';
import { ContactPage } from '../contact/contact';
 
@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = HomePage;
  tab2Root: any = AboutPage;
  tab3Root: any = ContactPage;
 
  constructor() {
 
  }
}

Here we are importing 3 pages HomePage, AboutPage and ContactPage and then assigning it to each tab.

src/pages/tabs/tabs.html template file

<ion -tabs>
  </ion><ion -tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion>
  <ion -tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion>
  <ion -tab [root]="tab3Root" tabTitle="Contact" tabIcon="contacts"></ion>

Which is then assigned as root pages on each tab. This is to maintain the sanity of navigation history. We’ll discuss about navigation in Ionic 2 in a separate video shortly.

src/index.html

< !DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8"/>
  <title>Ionic App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, 
        minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
  <meta name="format-detection" content="telephone=no"/>
  <meta name="msapplication-tap-highlight" content="no"/>
 
  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico"/>
  <link rel="manifest" href="manifest.json"/>
  <meta name="theme-color" content="#4e8ef7"/>
 
  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>
 
  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.log('Error', err));
    }
  -->
 
  <link href="build/main.css" rel="stylesheet"/>
 
</head>
<body>
 
  <!-- Ionic's root component and where the app will load -->
  <ion -app></ion>
 
  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>
 
  <!-- The bundle js is generated during the build process -->
  <script src="build/main.js"></script>
 
</body>
</html>

This file has some minimal configurations and links to some JavaScript library files. Ionic 2 application looks for ion-app tag present inside the body of index.html to kick-start the visuals of the project.

config.xml (located at the root of the project)

< ?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.technotip.radio" version="0.0.1" 
        xmlns="http://www.w3.org/ns/widgets" 
        xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>Radio</name>
  <description>Internet radio streaming live ..</description>
  <author email="my@mail.com" href="http://technotip.com/">SATISH</author>
 .
 .
 .
 .
</widget>

Using this file we can configure the display mode and other such things of the device for our application. We can also set the app name, description. author email id, name and the URL. We can set the id of the application which’ll be shown in the URL of the playstore once your app has been uploaded to the playstore. We have a radio application in the playstore which has an id com.technotip.radio You can visit our Radio Application and check the URL.

package.json (located at the root of our application)
This file has the list of our dependencies and plugins our application is using. It gets updated automatically when we install new plugins.

Important: Keep in mind that, whenever you are using any page component or data services in any of your project files, make sure to import it first. Also make sure to register its existence by importing it in src/app/app.module.ts file and listing it in specific sections which it belongs to.