Creating new Angular project and Installing Bootstrap in Angular

  • We can create a new project in Angular first using below commands.
sudo ng new my-dream-app
cd new my-dream-app

Then run the below command to install Bootstrap inside the new project.
Note : Below command will installl bootstrap locally into the newly create project.

sudo npm install --save bootstrap@4.3

Location of bootstrap.min.css file after installing bootstrap is <project_name>/node_modules/bootstrap/dist/css/bootstrap.min.css

Now we need to make angular aware of the bootstrap installed by giving the path of bootstrap.min.css in the angular.json config file.

The location of bootstrap.min.css should be inside project – project-name – architect – build – options – styles tag and add the string “node_modules/bootstrap/dist/css/bootstrap.min.css”

Now run start the server by runnning ns serve command in the root project folder via terminal

Now we can confirm if bootstrap is installed on to the project by hitting the URL : http://localhost:4200/ and opening the developer tools and navigate to <html> <head> <style> tag to view bootstrap, screenshot below.

Inheritance and Polymorphism in TypeScript

  • Just like other languages you can extend a classes which will have is a relationship with each other.
  • All the methods and data members are inherited from the parent class.
class Person{
    name : String;
    greet(){
        console.log("Hello Person");
    }
}
class Employee extends Person{
    empId : String;
    greet(){
        console.log("Hello Employee")
    }
    personGreet(){
        super.greet();
    }
}
var emp = new Employee();
emp.personGreet();
emp.greet();
var per : Person = new Employee();
emp.personGreet(); //greet on employee method
emp.name = "Tyson Gill" //inheriting the data memeber of parent class
emp.empId = "879869689698";

Classes in TypeScript

  • Classes in TypeScript is similar to that of most of the classes in other languages.
  • Classes are implemented in JavaScript as methods in the compiled .js code.
  • Classes have Constructors and new key word to declare an Object in TypeScript.

Example of Simple Class, data members and type creation in TypeScript

Methods in Classes

  • Just like we data members, we have member functions as well in TypeScript.
  • We can define data type of parameters and return type in these methods.

Constructors

  • Constructors in TypeScript can be create using keyword constructor()
  • We can only have one constructor in TypeScript
  • Constructors can be parameterized as well as empty.
class Person{
    private firstName : String;
    private lastName : String;
    public age : number;
    constructor(){
        this.firstName = "";
        this.lastName = "";
    }
    public setName(firstName : String, lastName : String){
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
var aPerson : Person= new Person(); //Declaring a variable of Type Person
aPerson.setName("Tyson","Gill")
aPerson.age = 70;
console.log(aPerson); 

After compilation the above code is converted into JavaScript and it looks like this :

Any and union type

Any Type

  • Any datatype says TypeScript to ignore type check on the variable.
  • This means that you can store string, boolean and number in the variable.
  • Any can mostly be used in migration project.

Example :

var a : any;
a = 10;
a = true;
a = "Hello World"

Union Type

  • Union Type can be used to define multiple data type to a variable.
  • This is achieved by using pipe separated data type.
  • Below is the example for the same.
var a : number | boolean;
a = 10;
a = true;

Setup for TypeScript Development environment.

  • Install VS Code as a text editor.
  • Install node js a requirement for TypeScript Compiler
  • Make sure npm(node packet manager) is installed along with node js.
  • Install TypeScript compiler using command
sudo npm install -g typescript ts-node

Test if the tyscript and ts-node using below command

sudo tsc --help

tsc for TypeScript compiler

Changes in VS Code for typescript :

  • install path – in command palette so that you can use vs code using code . command
  • Prettier Extension to be installed and enable format on save in settings
  • Format on Save in View -> Setting (search)
  • Theme sorlaris light

Typing with functions

As we know no data type check if made while creating functions in JavaScript but in type script we can do that by passing Types as parameters in function declaration.

Lets see first the traditional JavaScript function call example :

Ouput looks like this :

Now lets write the same function in TypeScript

function add(a : number , b : number){
    return a+b;
}
console.log("Adding two numbers : "+add(10,30));
console.log("Adding String and number : "+add("Hello",30));

The above code does not compile since we are trying to pass String insted of nunber

Hence after removing the line where String is given as parameter into the add function the code compiles are gives successful result

function add(a : number , b : number){
    return a+b;
}
console.log("Adding two numbers : "+add(10,30));

Optional and Default argument in Function

  • We can specify optional argument in TypeScript by adding ? after the variable name.
  • This optional argument always has to be at the end of the method parameter.
  • Multiple optional arguments are allowed.
  • By specifying the default value in the function parameter makes the parameter optional.
  • We can specify the default value by assigning value to it
    example function  add(a : number , b : number, c : number = 10) now c has default value has 10 and if 3rd parameter is not passed still it will be considered as 10.
/**
 * 
 * @param a 
 * @param b 
 * @param c - Optional parameter by adding ? in the function argument definition
 * Note : Optional argument can always be at the end of the function argument
 */
function add(a : number , b : number, c : number = 50,d? : number){
    if(d==null){
        d=0;
    }
    return a+b+c+d;
}
console.log("Adding two numbers, default and optional : "+add(10,20));
console.log("Adding three numbers and optional : "+add(10,20,30));
console.log("Adding four numbers : "+add(10,20,30,40));

Specifying function return type

  • The way to specify the return type of function is by adding a : type after closing bracket of the function parameters.
  • Syntax
    function functionName (a: type, b : type) : return_type{ }
  • If if add return type as number and pass return type as String then it will throw error while compilation
function add(a : number, b : number) : number{
    return "Hello";
}
function add(a : number, b : number) : number{
    return a+b;
}

Arrays and Tuples in TypeScript

Similar to other languages TypeScript also has arrays to store similar data types together.
Below is the example of primitive data type array.

var a : number[];
var b : boolean[];
var c : String[];

a = [1,2,3];
b = [true, false, true];
c = ["Hello","World"]

c.pop();
c.push("TypeScrpt")

Here pop() and push() are methods applicable on array in javascript

Tuples

In JavaScript, arrays are flexible i.e we can store any data type in an array. But to do similar thing in TypeScript we have something called Tuple which is used to store fixed data in it.

var demoTuple : [number,boolean];
demoTuple = [1,true];
demoTuple = [2,false];
//demoTuple = [1]; Error required in type '[number, boolean]'

In the above example we have defined a tuple that stored number and boolean, now if we store only number it gives us error saying required in type ‘[number, boolean]’

The restriction in the Tuple is you can store only set a values as defined during declaration unlike arrays where you can store n size of data in it.

Hello World in TypeScript

Create a workspace to store all your TypeScript files in it, and open up VS Code editor and open the folder in workspace using (File –> Open Folder or Ctrl+K and Ctrl+O)
Create new file with name hello-world.ts , ts here indicates TypeScript file. Write the below code inside it.

var fn = function () { return 'response'; };

Open up the terminal and now compile the hello-world.ts file using command below (Terminal can be opened up using CTRL+` in VS Code)

tsc hello-world.ts

After compilation is done a hello-world.js file will be created parallel to hello-world.ts file.This file is the compiled JavaScript code equivalent to that of TypeScript code.The code inside hello-world.js look like below

var fn = function () { return 'response'; };

To execute the js file run the below command

node hello-world.js

Defining Primitive types in TypeScript

You can indicate a var as a number, boolean or String using the below command.

var a : number;
var b : boolean;
var c : String;

a = 10;
b = true;
c= "Hello World";

If you assign a incorrect type to a variable then TypeScript compilation will fail
Example : Below

var a : number;
var b : boolean;
var c : String;

a = 10;
b = true;
c= 20;

Compilation of above code will give you error :

What is Angular?

  • Angular is a JavaScript Framework which allows you to create reactive Single-Page-Applications (SPAs).
    • Single-Page-Application(SPAs) is a web application that fits on a single page.
    • All HTML,JS and CSS is retrieved with a single page load.
    • Navigation between pages of the single page application is loaded within the same frame without refreshing the whole page.
    • It uses HTML5 and AJAX to achieve the smooth page navigation between pages in SPAs
  • Thus angular is used to make reactive front end applications which almost looks like mobile application i.e very fast everything happens instantly.
  • Single Angular creates SPAs all the data that is rendered is not hitting server everytime, it is java script that renders that data on the page.
  • And if we do need data from server then you just need to load it in the background so that user never leaves this experience of having a reactive web application.
  • Internally when you click a page on SPAs the java script changes the DOM(Document Object Model) during runtime and renders it for you. That is the reason you never see the refresh icon on the browser spin.

Why to use Angular? Advantages of using Angular.

  • Angular is mobile and desktop-ready, meaning you have one framework for multiple platform.
  • Angular presents you not only the tools but also design patterns to build your project in a maintainable way.
  • Angular uses java script but in a better way.Angular is built with TypeScript, which in turn relies on JS ES6. You don’t need to learn a totally new language, but you still receive features like static typing, interfaces, classes, namespaces, decorators etc.
  • Angular already has lots of tools to start designing the applications right away, so you need to reinvent the wheel or write the code from the scratch.
  • Angular promotes tight coupling between various components of the application.
  • Angular does not tightly couple application logic and presentation logic which makes markup much cleaner and simpler.
  • Angular is ment to be thoroughly tested and it supports both unit testing and end to end testing with the help of tools like Jasmine and Protractor.
  • Angular is actively maintained and has large community and also has large 3rd party tools to support angular development.

When to go for Angular ?

  • When you application is complex enough to justify it.
  • When you want to test client side as well.

Angular 1 vs Angular 2+

  • Angular 1 was the first angular framework which was developed base on java script.
  • Later Angular 2+ i.e angular 2 and above versions came in which was a complete rewrite from angular 1, angular 2+ were base on Type script