top
Easter Sale

Search

Ionic Tutorial

Before beginning with Ionic, it is essential to have good knowledge of Angular. Angular programs are written in TypeScript.  But before looking at TypeScript we will also take a brief look at Node JS. Node Js is a server environment that runs JavaScript. The easiest way to run TypeScript is within node.  Node comes with its package manager - npm - Node Package Manager. NPM is the world’s largest package repository. It is the most common mechanism to distribute open source software. TypeScript, Angular and Node are made available via node. At the most fundamental level it is important to get a sense of what TypeScript is and what the programming language looks like. This is done best by means of practical examples. It is recommended that you try the examples in this tutorial before proceeding to Ionic. From the TypeScript website...TypeScript is a “typed” superset of JavaScript. It compiles into plain JavaScript.  Ionic uses TypeScript because it uses Angular. And Angular uses TypeScript. Hence, the need to learn TypeScript.  Traditionally, enterprise languages have been written in object oriented programming languages that are scalable. The primary advantage of using an OOP language is that it can handle complexity well. As applications grow in size and age, they grow complex. The programming language should allow building large programs, while still staying modular. TypeScript, in contrast to JavaScript is Object Oriented.  JavaScript is a loosely typed language. This means that you do not need to specify what kind of data will be stored in a variable in advance.  TypeScript is strongly typed and forces you to specify the type for variables that you use. This static typing is optional. Code editors like Visual Studio Code offer enhanced support for TypeScript.  Further, JS files can be saved as TypeScript files. InstallationAs mentioned above, TypeScript is made available through node js. If you do not have node already installed, you can install it from: https://nodejs.org/en/download/Once you have node installed, you have node’s package manager available. TypeScript can be installed using: npm install -g TypeScript “-g” means that TypeScript is installed globally and can be accessed from any folder.  A further note on node TypeScript compiles to JavaScript and node executes the JavaScript files. To be precise, node is a JavaScript runtime environment, much like JRE for Java. It contains everything that JavaScript needs to run.  It is built on Chrome’s JavaScript V8 Engine. It converts JavaScript to Machine Code What does the JavaScript V8 Engine do in Chrome/ Node Heap - Allocates memory Call Stack - Records where in the program we are? Which function is being called? It is single threaded, meaning, it does one thing at a time Handles Blocking Behaviour- In the past, the entire browser used to “freeze” when there was some processing going on. These items are queued in an “Event Loop” until the stack is empty. WebAPIs - It offers libraries like AJAX. DOM,Why not write in JS directlyEach browser has its own JavaScript Engine. Chrome runs V8, Firefox runs SpiderMonkey, and Internet Explorer, Chakra. Each has its own compatibility issues.https://kangax.github.io/compat-table/es6/TypeScript compiles to JavaScript standard ECMA Script. Browsers are compliant at different levels. Thus TypeScript can run on any browser. TypeScript offers a better set of tools like Intellisense, Debugging, etc. Angular and TypeScript Angular 2 would is a complete rewrite of AngularJS, which was written in JavaScript. Microsoft added annotations to TypeScript language, and making it the language for the development of the Angular 2 framework itself. Code editor/ IDE Download and install Visual Studio Code from https://code.visualstudio.com/ The TypeScript Language With this background, we are good to get started with TypeScript. This will be a brief introduction so that we know enough to get introduced to Angular/ Ionic. Hello World Create a new folder TypeScriptTutorial Open Visual Studio Code and import the folderAnd create a new file (Hello.ts) by right clicking on the folder in the folder and typeconsole.log(“Hello World”)Save the fileOpen the integrated terminaltype tsc hello.tsYou will notice that TypeScript has been compiled into a JavaScript file hello.jsOn the command prompt run node hello. The JavaScript engine within node will run the JavaScript file and print “Hello World” On the consoleIn addition to doing a “hello world” in TypeScript, you now know how to import a folder and create files in TypeScript. You also now know how to run commands within the editor. VariablesA variable is used to store, retrieve and manipulate information in a programming language. TypeScript uses the key words let and const  to declare variables.let greeting = “hello world” console.log(greeting) const greeting2  = “hello world” console.log(greeting2)A variable declared using Const needs to be initialized and it cannot be reassigned.In the images above, it is seen that Visual Studio Code flags the variable “a” with an error when it is not initialized and when it is reassigned a value. Variable typesTypeScript supports 3 data types. As mentioned earlier using data types is optional.  BooleanNumberStringlet name : string = “Josh”  let age : number = 22  let isStudent : boolean = true Variables can be assigned as null or undefined let name : string = null let name : string = undefinedTypes are checked in compile timeAllows intellisense in the editor. Intellisense is Microsoft’s way of intelligent code completion.ExpressionsAn expression is a combination of operators and operands. Operands can be constants, variables or other expressions.a= 12 * b + c;12, b, c are operands in the expression and =,*,+ are operators.TypeScript supports the following operators:Arithmetic operators+, -, *, /, %, ++, --Logical operators&& (AND), || (OR), ! (NOT)Relational operators>, <, >=, <=, != (not equal), == (equal)Assignment operators=,  +=, -=, *=, /=, %=Ternary/conditional operatorlet t = 10>20?”smaller”:”larger”; Will store “smaller” in tTypeOf Operator“ var a = 12; console.log(typeof a)” will return “number”Bitwise operators& (AND). | (OR), ^ (XOR), ~ ( Not), << (Left Shift), >> (Right Shift), >>> (Right shift with Zero)Template Strings A template string is a string which is enclosed within back-tick characters (`). It can include expressions within ${ }. TypeScript replaces placeholders with real values. Template strings are a better option to use when compared to string concatenation. let name = 'Josh'; console.log('name ' + name) let statement = `I am ${name}` console.log(statement)The output will be:Arrays An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as a number or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched. You can declare an array in 2 ways: let list1 :number[] = [1,2,3] let list2: Array<number> = [1,2,3]String arrayslet list3: Array<string> = ['1','2','3'] let list4: Array<string> = [`1   ${list2}`,'2','3'] console.log(list4)Any Any is used when you are not sure what the data type is. When a variable is declared as “any” it can be assigned any value let a :any;  a = "200";  a = 200;  a = false;  console.log(a) TupleA tuple is an array of fixed length. It allows multiple types in a single array.let student : [string,number] = ['josh',2]console.log(student)Type Inference Type inference happens in TypeScript when there is no explicit data type specified and the variable is initialized.  The following will worklet aa = truea= 1 The following will throw an error since the type is inferred as number;let a = 10a = true Union of TypesTypeScript allows multiple types for a single variable. You can achieve this by using the pipe symbol in the variable declaration. This is normally used when the data stored in the variable is not under your control.  In comparison to “any”, it allows a higher degree of control. It also provides intellisense support.  let a :number|string;a=20;a="zoom" Below is the intellisense for a when is a union of number and stringBelow is the intellisense when it is anyFunctionsIn any programming language, functions define how to do things.  A simplest function will look like this: function printHello(){  console.log('Hello')  }  printHello() A function can receive parameters as below function printHello(message){  console.log(message)  }  printHello('hello') Parameter is declared with a type function printHello(message:string){  console.log(message)  }  printHello('hello') Multiple Parameters function printHello(message:string, name:string){  console.log(message + " " + name)  }  printHello('hello', 'josh') Optional ParametersOptional parameters are suffixed with a question mark function printHello(message:string, name?:string){  if(name)  console.log(message + " " + name)  else  console.log(message )  }  printHello('hello', 'josh')  printHello('hello, how are you' ) The output will beDefault values for parameters If a parameter is not passed, it can be initialized with a default valuefunction printHello(message:string = 'Hello', name?:string){ if(name) console.log(message + " " + name) else console.log(message ) } printHello()Defining return types A return type is defined as below function printHello(message:string, name:string):string{  if(name)  return message + " " + name  else  return message   }  let message = printHello("Hello", "Josh");  console.log(message); ClassesA class is a template for an object and an object is an instance of a class.  Variables defined within a class are called Instance Variables Code is contained in Methods Methods and Variables are called Members Variables are accessed and acted upon by the methods Data of one object is separate and unique from any other object Below is an example of a TypeScript class class Person{      firstName:string;      lastName:string;     sayHello(){          console.log("hello " + this.firstName)      } sayGoodBye(){          console.log("bye " + this.firstName)      }  } firstName and lastName are instance variables.  sayHello and sayGoodbye are the methods that contain the code of the class.  firstName, lastName, sayHello() and sayGoodBye() are the members.  The variables are accessed and acted upon by the method; An instance of the class is created as follows let max = new Person(); max.firstName = "Max"; max.lastName = "Payne"; max.sayHello(); console.log(max);Constructors Constructors are used to initialize classes. They are automatically called when the class is created class Person{      firstName:string;  lastName:string; constructor(firstName:string, lastName?:string){          this.firstName = firstName;          this.lastName = lastName;      }      sayHello(){          console.log("hello " + this.firstName)      }  sayGoodBye(){          console.log("bye " + this.firstName)      }  }  let max = new Person("Max", "Payne");  max.sayHello();  console.log(max);Optional propertiesA class can have optional properties as follows    lastName?:string; Array of objects Objects arrays can be initialized as follows: let persons :Person[] =   [{"firstName":"Quintin","lastName":"Tarantino"},  {"firstName":"Steven","lastName":"Spielberg"},  {"firstName":"Christopher","lastName":"Nolan"}] They can be looped through using a for loop as follows for(let i=0; i<persons.length; i++){      console.log(`${i} ${persons[i].firstName} ${persons[i].lastName}`)  }Or using a while loop let i=0;  while(i<persons.length){      console.log(`${i} ${persons[i].firstName} ${persons[i].lastName}`)      i++;  }InterfacesInterfaces specify “what” a class must do, but not “how”. They define the structure of a class.  interface Person{     firstName:string;     lastName:string;     sayHello(); sayGoodBye(); }The implementation of sayHello and sayGoodBye is upto the classes that implement the interface to define. Class SimplePerson implements Person{      firstName:string;      lastName:string;      sayHello(){  console.log(“Simple Hello”;      }  sayGoodBye(){  console.log(“Simple Bye”;      }  }  Class ComplexPerson implements Person{      firstName:string;      lastName:string;      sayHello(){  console.log(“Complex Hello”;      }  sayGoodBye(){  console.log(“Complex Bye”;      }  } Modules Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported from the module and imported into the program using them In the above example, the interface Person will not be accessible unless it is imported. export interface Person {      firstName:string;  lastName:string;  sayHello();  sayGoodBye();  }The class implementing the interface has to import the module import { Person } from "./helloInterface";  class Person3 implements Person{The key points to be noted here are the export keyword and import statement A note on compilationTypeScript applies object oriented programming to JavaScript. The process of conversion of TypeScript to JavaScript is an example of transpilation.One of the key advantages of transpilation is that it allows us to use future features of JavaScript today.
logo

Ionic Tutorial

Introduction to TypeScript

Before beginning with Ionic, it is essential to have good knowledge of Angular. Angular programs are written in TypeScript.  

But before looking at TypeScript we will also take a brief look at Node JS. Node Js is a server environment that runs JavaScript. The easiest way to run TypeScript is within node.  

Node comes with its package manager - npm - Node Package Manager. NPM is the world’s largest package repository. It is the most common mechanism to distribute open source software. TypeScript, Angular and Node are made available via node. 

At the most fundamental level it is important to get a sense of what TypeScript is and what the programming language looks like. This is done best by means of practical examples. It is recommended that you try the examples in this tutorial before proceeding to Ionic. 

From the TypeScript website...

TypeScript in Ionic

  • TypeScript is a “typed” superset of JavaScript. It compiles into plain JavaScript.  
  • Ionic uses TypeScript because it uses Angular. And Angular uses TypeScript. Hence, the need to learn TypeScript.  
  • Traditionally, enterprise languages have been written in object oriented programming languages that are scalable. The primary advantage of using an OOP language is that it can handle complexity well. As applications grow in size and age, they grow complex. The programming language should allow building large programs, while still staying modular. TypeScript, in contrast to JavaScript is Object Oriented.  
  • JavaScript is a loosely typed language. This means that you do not need to specify what kind of data will be stored in a variable in advance.  
  • TypeScript is strongly typed and forces you to specify the type for variables that you use. This static typing is optional. 
  • Code editors like Visual Studio Code offer enhanced support for TypeScript.  
  • Further, JS files can be saved as TypeScript files. 

Installation

As mentioned above, TypeScript is made available through node js. If you do not have node already installed, you can install it from: 

https://nodejs.org/en/download/

Once you have node installed, you have node’s package manager available. TypeScript can be installed using: 

  • npm install -g TypeScript 
  • “-g” means that TypeScript is installed globally and can be accessed from any folder.  

A further note on node 

TypeScript compiles to JavaScript and node executes the JavaScript files. To be precise, node is a JavaScript runtime environment, much like JRE for Java. It contains everything that JavaScript needs to run.  

It is built on Chrome’s JavaScript V8 Engine. It converts JavaScript to Machine Code 

What does the JavaScript V8 Engine do in Chrome/ Node 

  • Heap - Allocates memory 
  • Call Stack - Records where in the program we are? Which function is being called? 
  • It is single threaded, meaning, it does one thing at a time 
  • Handles Blocking Behaviour- In the past, the entire browser used to “freeze” when there was some processing going on. These items are queued in an “Event Loop” until the stack is empty. 
  • WebAPIs - It offers libraries like AJAX. DOM,

Why not write in JS directly

Each browser has its own JavaScript Engine. Chrome runs V8, Firefox runs SpiderMonkey, and Internet Explorer, Chakra. Each has its own compatibility issues.

https://kangax.github.io/compat-table/es6/

  • TypeScript compiles to JavaScript standard ECMA Script. Browsers are compliant at different levels. Thus TypeScript can run on any browser. 
  • TypeScript offers a better set of tools like Intellisense, Debugging, etc. 

Angular and TypeScript 

Angular 2 would is a complete rewrite of AngularJS, which was written in JavaScript. Microsoft added annotations to TypeScript language, and making it the language for the development of the Angular 2 framework itself. 

Code editor/ IDE 

Download and install Visual Studio Code from https://code.visualstudio.com/ 

The TypeScript Language 

With this background, we are good to get started with TypeScript. This will be a brief introduction so that we know enough to get introduced to Angular/ Ionic. 

Hello World 

  • Create a new folder TypeScriptTutorial 
  • Open Visual Studio Code and import the folder

New folder TypeScript

  • And create a new file (Hello.ts) by right clicking on the folder in the folder and type
    console.log(“Hello World”)

new folder TypeScript

  • Save the file
  • Open the integrated terminal

new folder TypeScript

new folder TypeScript

  • type tsc hello.ts
  • You will notice that TypeScript has been compiled into a JavaScript file hello.js
  • On the command prompt run node hello. The JavaScript engine within node will run the JavaScript file and print “Hello World” On the console

new folder TypeScript

In addition to doing a “hello world” in TypeScript, you now know how to import a folder and create files in TypeScript. You also now know how to run commands within the editor. 

Variables

A variable is used to store, retrieve and manipulate information in a programming language. TypeScript uses the key words let and const  to declare variables.

let greeting = “hello world”
console.log(greeting)

const greeting2  = “hello world”
console.log(greeting2)

A variable declared using Const needs to be initialized and it cannot be reassigned.

new folder TypeScript

new folder TypeScript

In the images above, it is seen that Visual Studio Code flags the variable “a” with an error when it is not initialized and when it is reassigned a value. 

Variable types

TypeScript supports 3 data types. As mentioned earlier using data types is optional.  

  • Boolean
  • Number
  • String
let name : string = “Josh” 
let age : number = 22 
let isStudent : boolean = true 
  • Variables can be assigned as null or undefined 
let name : string = null
let name : string = undefined
  • Types are checked in compile time

compile time

  • Allows intellisense in the editor. Intellisense is Microsoft’s way of intelligent code completion.

 intelligent code completion.

Expressions

An expression is a combination of operators and operands. Operands can be constants, variables or other expressions.

variables or other expressions

a= 12 * b + c;

12, b, c are operands in the expression and =,*,+ are operators.

TypeScript supports the following operators:

Arithmetic operators+, -, *, /, %, ++, --
Logical operators&& (AND), || (OR), ! (NOT)
Relational operators>, <, >=, <=, != (not equal), == (equal)
Assignment operators=,  +=, -=, *=, /=, %=
Ternary/conditional operatorlet t = 10>20?”smaller”:”larger”; Will store “smaller” in t
TypeOf Operator“ var a = 12; console.log(typeof a)” will return “number”
Bitwise operators& (AND). | (OR), ^ (XOR), ~ ( Not), << (Left Shift), >> (Right Shift), >>> (Right shift with Zero)

Template Strings 

A template string is a string which is enclosed within back-tick characters (`). It can include expressions within ${ }. TypeScript replaces placeholders with real values. Template strings are a better option to use when compared to string concatenation. 

let name = 'Josh';
console.log('name ' + name)
let statement = `I am
${name}`
console.log(statement)

The output will be:

variables or other expressions

Arrays 

An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as a number or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched. 

You can declare an array in 2 ways: 

let list1 :number[] = [1,2,3]
let list2: Array<number> = [1,2,3]

String arrays

let list3: Array<string> = ['1','2','3']
let list4: Array<string> = [`1  
${list2}`,'2','3']
console.log(list4)

Arrays

Any 

Any is used when you are not sure what the data type is. When a variable is declared as “any” it can be assigned any value 

let a :any; 
a = "200"; 
a = 200; 
a = false; 
console.log(a) 

Tuple

A tuple is an array of fixed length. It allows multiple types in a single array.
let student : [string,number] = ['josh',2]
console.log(student)

Tuple

Type Inference 

Type inference happens in TypeScript when there is no explicit data type specified and the variable is initialized.  

The following will work
let a
a = true
a= 1 

The following will throw an error since the type is inferred as number;
let a = 10
a = true 

Union of Types

TypeScript allows multiple types for a single variable. You can achieve this by using the pipe symbol in the variable declaration. This is normally used when the data stored in the variable is not under your control.  

In comparison to “any”, it allows a higher degree of control. It also provides intellisense support.  

let a :number|string;
a=20;
a="zoom" 

Below is the intellisense for a when is a union of number and string

intellisense

Below is the intellisense when it is any

intellisense

Functions

In any programming language, functions define how to do things.  

  • A simplest function will look like this: 
function printHello(){ 
      console.log('Hello') 
} 
printHello() 
  • A function can receive parameters as below 
function printHello(message){ 
       console.log(message) 
} 
printHello('hello') 
  • Parameter is declared with a type 
function printHello(message:string){ 
       console.log(message) 
} 
printHello('hello') 
  • Multiple Parameters 
function printHello(message:string, name:string){ 
       console.log(message + " " + name) 
} 
printHello('hello', 'josh') 
  • Optional Parameters
    Optional parameters are suffixed with a question mark 
function printHello(message:string, name?:string){ 
       if(name) 
           console.log(message + " " + name) 
       else 
         console.log(message ) 
} 
printHello('hello', 'josh') 
printHello('hello, how are you' ) 

The output will be

Typescript code

  • Default values for parameters 

If a parameter is not passed, it can be initialized with a default value

function printHello(message:string = 'Hello', name?:string){
      if(name)
            console.log(message + " " + name)
      else
           console.log(message )
}
printHello()

Typescript code

  • Defining return types 

A return type is defined as below 

function printHello(message:string, name:string):string{ 
      if(name) 
           return message + " " + name 
      else 
           return message  
} 
let message = printHello("Hello", "Josh"); 
console.log(message); 

Classes

A class is a template for an object and an object is an instance of a class.  

  • Variables defined within a class are called Instance Variables 
  • Code is contained in Methods 
  • Methods and Variables are called Members 
  • Variables are accessed and acted upon by the methods 
  • Data of one object is separate and unique from any other object 

Below is an example of a TypeScript class 

class Person{ 
    firstName:string; 
    lastName:string;

    sayHello(){ 
        console.log("hello " + this.firstName) 
    }

     sayGoodBye(){ 
        console.log("bye " + this.firstName) 
    } 
} 
  • firstName and lastName are instance variables.  
  • sayHello and sayGoodbye are the methods that contain the code of the class.  
  • firstName, lastName, sayHello() and sayGoodBye() are the members.  
  • The variables are accessed and acted upon by the method; 

An instance of the class is created as follows 

let max = new Person();
max.firstName = "Max";
max.lastName = "Payne";
max.sayHello();
console.log(max);

Typescript code

Constructors 

Constructors are used to initialize classes. They are automatically called when the class is created 

class Person{ 
    firstName:string; 
    lastName:string;

       constructor(firstName:string, lastName?:string){ 
        this.firstName = firstName; 
        this.lastName = lastName; 
    } 
    sayHello(){ 
        console.log("hello " + this.firstName) 
    } 
     sayGoodBye(){ 
        console.log("bye " + this.firstName) 
    } 
} 
let max = new Person("Max", "Payne"); 
max.sayHello(); 
console.log(max);

Typescript code

Optional properties

A class can have optional properties as follows 

   lastName?:string; 

Array of objects 

Objects arrays can be initialized as follows: 

let persons :Person[] =  
[{"firstName":"Quintin","lastName":"Tarantino"}, 
{"firstName":"Steven","lastName":"Spielberg"}, 
{"firstName":"Christopher","lastName":"Nolan"}] 

They can be looped through using a for loop as follows 

for(let i=0; i<persons.length; i++){ 
    console.log(`${i} ${persons[i].firstName}
${persons[i].lastName}`) 
}

Or using a while loop 

let i=0; 
while(i<persons.length){ 
    console.log(`${i} ${persons[i].firstName}
${persons[i].lastName}`) 
    i++; 
}

Interfaces

Interfaces specify “what” a class must do, but not “how”. They define the structure of a class.  

interface Person{
    firstName:string;
    lastName:string;
    sayHello();
    sayGoodBye();
}
The implementation of sayHello and sayGoodBye is upto the classes that implement the interface to define.

Class SimplePerson implements Person{ 
    firstName:string; 
    lastName:string; 
    sayHello(){ 
             console.log(“Simple Hello”; 
    } 
    sayGoodBye(){ 
            console.log(“Simple Bye”; 
    } 
} 
Class ComplexPerson implements Person{ 
    firstName:string; 
    lastName:string; 
    sayHello(){ 
           console.log(“Complex Hello”; 
    } 
    sayGoodBye(){ 
        console.log(“Complex Bye”; 
    } 
} 

Modules 

Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported from the module and imported into the program using them 

In the above example, the interface Person will not be accessible unless it is imported. 

export interface Person { 
    firstName:string; 
     lastName:string; 
     sayHello(); 
     sayGoodBye(); 
}

The class implementing the interface has to import the module 

import { Person } from "./helloInterface"; 
class Person3 implements Person{

The key points to be noted here are the export keyword and import statement 

A note on compilation

TypeScript applies object oriented programming to JavaScript. The process of conversion of TypeScript to JavaScript is an example of transpilation.

One of the key advantages of transpilation is that it allows us to use future features of JavaScript today.

Leave a Reply

Your email address will not be published. Required fields are marked *