Monday, November 28, 2016

Angular 2 Part 5.3 - HTTP

In part 5.3, we are going to fetch our data using HTTP JSON call instead of mock data.

There are 5 steps to make it happen:

1. Create a JSON data file to simulate the data from the server - car-parts.json.
{
 "data" : [
  {
   "id":1,
   "name":"Super Tires",
   "price":2.0,
   "description":"These tires are the very best",
   "inStock":5,
   "image":"/images/example1.png",
   "featured":false,
   "quantity":0
  },
  {
   "id":2,
   "name":"Reinforced shocks",
   "price":4.99,
   "description":"Shock made from krytonite",
   "inStock":4,
   "image":"/images/example2.png",
   "featured":true,
   "quantity":0
  },
  {
   "id":3,
   "name":"Padded Seats",
   "price":2,
   "description":"Super soft scats for a smooth ride.",
   "inStock":0,
   "image":"/images/example3.png",
   "featured":false,
   "quantity":0
  }
 ]
}

2. We need to include HTTP and RxJS Libraries. The HTTP library provides the get call we will use to call across the internet. The RxJS library stands for Reactive Extensions and provides some advance tooling for our HTTP Calls. If you used the 5 minutes QuickStart, you have already included these libraries using systemjs.config.js.

3. Import HTTPModule in main.ts. We can skip adding HTTP as provider because it had already added in HTTPModule.
import {NgModule, Component} from '@angular/core';
import {AppComponent} from './app.component';
import {CarPartComponent} from './car-parts.component';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import { RacingDataService } from './racing-data.service';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

@NgModule ({
  imports:      [ BrowserModule, FormsModule, HttpModule ], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent ], // Import dependencies.
  bootstrap:    [ AppComponent ], // Indicate first component to launch.
  providers:  [ RacingDataService ] // Now all subcomponents can ask for (inject) our RacingDataService.
})

class AppModule {}

// Start the application in web browser.
platformBrowserDynamic().bootstrapModule(AppModule);
4. Now we can inject HTTP and using it in racing-data.service.ts.
import { CARPARTS } from './mocks';
import {CarPart} from './car-part';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class RacingDataService {

 constructor(private http: Http) {}

 getCarParts() {
  return this.http.get('app/car-parts.json')
   .map(response => <CarPart[]>response.json().data);
 }

}
response = data returned.
<CarPart[]> = Tells our TypeScript compiler to treat this like an arrays of CarPart.
response.json() = For each response, parse the string into JSON.
.data = The array we want is under the data keyword.

5. Since our service returns an observable, we need to subscribe to that data stream and tell our component what to do when our data arrives.
import {Component} from '@angular/core';
import {CarPart} from './car-part';
import { RacingDataService } from './racing-data.service';

@Component({
  selector: "car-parts", // Display in selector defined in app.component.ts
  templateUrl: "app/car-parts.component.html",
  styleUrls: ["app/car-parts.component.css"]
})

export class CarPartComponent {
  carParts : CarPart[];

  // Declare a constructor
  constructor (private racingDataService: RacingDataService) {}

  ngOnInit() {
    this.racingDataService.getCarParts()
      .subscribe(carParts => this.carParts = carParts); // When carParts arrive on our data stream, set it equal to our local carParts array.
  }

  totalCarParts(){
    let sum = 0;
      if(Array.isArray(this.carParts)) {
        for (let carPart of this.carParts) {
          sum += carPart.inStock;
        }
      };
    return sum;
  }

  upQuality(carPart){
    if (carPart.quantity < carPart.inStock) carPart.quantity++;
  }
 
  downQuality(carPart){
    if (carPart.quantity != 0) carPart.quantity--;
  }

}

That's all for Angular 2 sample and I hope you all enjoyed. Here are some tools you might interest.

  • Angualr Angury an Angular 2 debugging tool.
  • Angular CLI - Angular Command Line Interface for developer kicks start project really fast.
Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 5.2 - Service using Dependency Injector

In Part 5.1, we introduced the simplest way to create service. However, this is yet a best solution because we need to create new RacingDataService every time when we need to fetch the data. This would used up more memory.

This is where dependency injection come in. When you run Angular 2 application, it creates a dependency injector. An injector is in charge of knowing how to create and send things.

One of the advantages is that dependency injection know how to resend the same service if the injector already created a service.

There are 3 steps to make all work in our example:

1. Add the injectable decorator to racing-data.service.ts.
...
import { Injectable } from '@angular/core';

@injectable()
...

2. Let our injector know about our service by naming it as a provider in main.ts
@NgModule ({
  imports:      [ BrowserModule, FormsModule, HttpModule ], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent ], // Import dependencies.
  bootstrap:    [ AppComponent ], // Indicate first component to launch.
  providers:  [ RacingDataService ] // Now all subcomponents can ask for (inject) our RacingDataService.
})

3. Inject the dependency into our car-parts.component.ts
export class CarPartComponent {
  carParts : CarPart[];

  // Declare a constructor
  constructor (private racingDataService: RacingDataService) {}

  ngOnInit() {
    this.racingDataService.getCarParts()
  }

  ...
}

Now our application is more scalable because our dependencies aren't strongly tied our classes.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 5.1 - Service

Service is used to organize and share code across your app, and they's re usually where you create your data access.

In our car part example, we are using mock file for data loading. Actually this is not a very good solution because we need to import mock in every file that need the data. Also, it is not easy to switch between real and mock data. This sort of data loading is best left to service classes.

Let create the simplest service by creating racing-data.services.ts. The flow will be car-parts.component.ts -> racing-data.services.ts -> mock.ts.

Here is our racing-data.services.ts:
import { CARPARTS } from './mocks';

export class RacingDataService {

 getCarParts() {
  return CARPARTS ;
 }
}

Our car-part.component.ts will lookup the new created racing-data.service.ts instead of mock.ts.
...
import { RacingDataService } from './racing-data.service';
...

export class CarPartComponent {
  ...
  ngOnInit() {
   let racingDataService = new RacingDataService();
   this.racingDataService.getCarParts()
  }
  ...
}

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 4.3 - Two-way Binding

In Part 4.3, I am going to introduce two-way binding where value keeps in sync in Javascript and HTML.

In our car part example, I am going to add a text field for quantity. User can fill up a quantity or click on plus / minus button to purchase. The value in the text field and buttons is in sync.

...
<input type="text" [(ngModel)]="carPart.quantity">
...
We import FormsModule in main.ts.

...
import { FormsModule } from '@angular/forms';

@NgModule ({
  imports:      [ BrowserModule, FormsModule], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent], // Import dependencies.
  bootstrap:    [ AppComponent ], // Indicate first component to launch.
  providers:  [RacingDataService] // Now all subcomponents can ask for (inject) our RacingDataService.
})
...

ngModel allows having one command to express two-way data binding. The syntax for two-way binding is [()], and sometimes called banana in a box.

Important to know when we are using ngModel syntax, we only set it equal to a data properly. Example:

[(ngModel)] = "user.age"
[(ngModel)] = "firstname"

You can not set ngModel to a component's method. Example:

[(ngModel)] = "fullname()"

Two-way binding means that if the component property is modified inside the component (Javascript) or inside our web page (HTML), it will stay in sync.

To summary on binding syntax:
  • [] - JavaScript to HTML binding
  • () - HTML to Javascript binding
  • [()] - Two-way binding binding.

Tuesday, November 22, 2016

Angular 2 Part 4.2 - Event Binding

In Part 4.1, I covered Property Binding and Class Binding. Both is JavaScript to HTML data flow.

In Part 4.2, I am going to introduce Event Binding which is HTML to JavaScript data flow. Any standard DOM Event can be listened for by wrapping it in parentheses and removing the "on" at the beginning of the word. Example:
  • <div (mouseover)="call()">
  • <input (blur)="call()">
  • <input (focus)="call()">
  • <input type="text" (keydown)="call()">
  • <form (submit)="call()">
Sometime, you need additional event data like which key is pressed or where the mouse is on the screen. We can pass it in to our component method with $event. Example:
<input type="text" (keydown)="showKey($event)">

showKey(event){
  //Prompt on key is pressed
  alert(event.keycode); 
}
<h2 (mouseover)="getCoord($event)">Hover Me</h2>

getCoord(event){
  // Display mouse X and Y coordinate.
  consolo.log(event.clientx + ", " + event.clienty);
}
I am going to add plus and minus button and bind this 2 buttons into a method in our car part example.

We add quantity property into our model.
export class CarPart {
  ...
  quantity:number;
}
Add quantity data into mock.ts.
export const CARPARTS : CarPart[] = [{ 
  "id":1,
  ...
  "quantity":0
},
{
  "id":2,
  ...
  "quantity":0
},
{
  "id":3,
  ...
  "quantity":0
}] // Example of object
Add 2 methods into car-parts.component.ts.
export class CarPartComponent {
  carParts : CarPart[];
  ngOnInit() {
    this.carParts = CARPARTS;
  }

  totalCarParts(){
    let sum = 0;
    for (let carPart of this.carParts) {      sum += carPart.inStock;
    }
    return sum;
  }

  upQuality(carPart){
    if (carPart.quantity < carPart.inStock) carPart.quantity++;
  }

  downQuality(carPart){
    if (carPart.quantity != 0) carPart.quantity--;
  }
}
Add 2 buttons into car-parts.component.html and bind to our created methods on click event.
<li *ngFor="let carPart of carParts" [class.featured]="carPart.featured">
  <h2>{{carPart.name | uppercase}}</h2>
    <img [src]="carPart.image">
    <p class="description">{{carPart.description}}</p>
    <p class="price">{{carPart.price | currency:"EUR":true}}</p>
    <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
    <p *ngIf="carPart.inStock === 0">Out of stock</p>
    <p><button (click)="downQuality(carPart)">-</button> {{carPart.quantity}} <button (click)="upQuality(carPart)">+</button></p>
</li>
Here is out put:




















Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 4.1 - Property and Class Binding

In Part 4, we are going to demonstrate binding in Angular. There are 3 different ways that data can flow (bind):
  1. JavaScript to HTML - Like we have been doing with property from our components.
  2. HTML to JavaScript - Like a mouse click, hover or key press.
  3. Both way - Like a text box that should stay in sync.
First, let me introduce Property Binding by adding an image. Property binding allows us to bind Component Properties to any DOM Element Properties. What we need to do is add [] into the DOM Element Properties. Any update to the Component Property value will update the DOM Property, but not vise versa - that's why it's "One way binding".

We add an image property into our model.
export class CarPart {
  id:number;
  name:String;
  price: number;
  description:String;
  inStock:number;
  image:String;
}
In our mocks.ts, we add image data.
export const CARPARTS : CarPart[] = [{ 
  "id":1,
  "name":"Super Tires",
  "price":2.0,
  "description":"These tires are the very best",
  "inStock":5,
  "image":"/images/example1.jpg"
},
{
  "id":2,
  "name":"Reinforced shocks",
  "price":4.99,
  "description":"Shock made from krytonite",
  "inStock":4,
  "image":"/images/example2.jpg"
},
{
  "id":3,
  "name":"Padded Seats",
  "price":2,
  "description":"Super soft scats for a smooth ride.",
  "inStock":0,
  "image":"/images/example3.jpg"
}] // Example of object
Here we add our images into car-parts.component.html.
<li *ngFor="let carPart of carParts">
  <h2>{{carPart.name | uppercase}}</h2>
  <img [src]="carPart.image">
  <p class="description">{{carPart.description}}</p>
  <p class="price">{{carPart.price | currency:"EUR":true}}</p>
  <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
  <p *ngIf="carPart.inStock === 0">Out of stock</p>
</li>
Here are the additional Property Binding example:
  • <div [hidden]="!user.isAdmin">Secret</div>
  • <button [disable]="isDisabled">Purchase</button>
  • <img [alt]="image.description">
Next, I am going to introduce Class Binding by adding CSS Class on featured product. Class Binding allows us to specify a CSS Class to add to a DOM Element if a Component Property is True.

We add a featured property into our model.
export class CarPart {
  id:number;
  name:String;
  price: number;
  description:String;
  inStock:number;
  image:String;
  featured:boolean;
}
In our mocks.ts, we add feature data. Only 1 product is featured.
export const CARPARTS : CarPart[] = [{ 
  "id":1,
  ...
  "featured":false
},
{
  "id":2,
  ...
  "featured":true
},
{
  "id":3,
  ...
  "featured":false
}] // Example of object
In our car-parts.component.css, we add featured class.
.featured{
  border: 1px solid black;
}
Here we add our feature CSS Class into car-parts.component.html.
<li *ngFor="let carPart of carParts" [class.featured]="carPart.featured">
  <h2>{{carPart.name | uppercase}}</h2>
  <img [src]="carPart.image">
  <p class="description">{{carPart.description}}</p>
  <p class="price">{{carPart.price | currency:"EUR":true}}</p>
  <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>  <p *ngIf="carPart.inStock === 0">Out of stock</p>
</li>
Here is the output where featured product's has border.




















If carPart.featured is true, then featured class is added.

If carPart.featured is false, then featured class is removed.

The format for Class Binding is [class.'name if the CSS Class'] = Component Property.

To overwrite the whole class, you can use this format ['name if the CSS Class'] = Component Property.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 3.3 - Model & Mock

In TypeScript, we can use classes to model our data. This helps us specify class property types that help our compiler ensure we're writing good code. I am going to model our car part by creating car-part.ts.

car-parts.ts
export class CarPart {
  id:number;
  name:String;
  price: number;
  description:String;
  inStock:number;
}
Mock is to separate our data file from component. It is good practice to keep our mock data separate from our model and component. I am going to move our data to mock.ts.

mock.ts
import {CarPart} from './car-part';

export const CARPARTS : CarPart[] = [{ 
  "id":1,
  "name":"Super Tires",
  "price":2.0,
  "description":"These tires are the very best",
  "inStock":5
},
{
  "id":2,
  "name":"Reinforced shocks",
  "price":4.99,
  "description":"Shock made from krytonite",
  "inStock":4
},
{
  "id":3,
  "name":"Padded Seats",
  "price":2,
  "description":"Super soft scats for a smooth ride.",
  "inStock":0
}] // Example of object
Now we going to integrate car-parts.ts and mock.ts into our car-parts.component.ts.
import {Component} from '@angular/core';
import {CarPart} from './car-part';
import {CARPARTS} from './mocks';

@Component({
  selector: "car-parts", // Display in selector defined in app.component.ts
  templateUrl: "app/car-parts.component.html",
  styleUrls: ["app/car-parts.component.css"]
})

export class CarPartComponent {  
  carParts : CarPart[];

  ngOnInit() {
    this.carParts = CARPARTS;
  }

  totalCarParts(){
    let sum = 0;
    for (let carPart of this.carParts) {
      sum += carPart.inStock;
    }
    return sum;
  }
}
ngOnInit() is invoked after the component is constructed and is the best place to initialize properly value.

For whole Part 3, we don't add any new functionality, but our code now is more easy to maintenance and scale. Let's look at our files structure.

  • index.html - Include <my-app> and load main.ts.
  • app\main.ts - Import and bootstraps our first component in app.component.ts.
  • app\app.component.ts - Load the header and sub component in car-parts.component.ts.
  • app\car-parts.component.ts - Our JavaScript.
  • app\car-part.ts - The data model.
  • app\mocks.ts - The fake data.
  • app\car-parts.component.html
  • app\car-parts.component.css
Download Car Part Source:

Monday, November 21, 2016

Angular 2 Part 3.2 - Component HTML & CSS

Our application does not look nice without CSS decoration. I am going to add CSS into our component decorator by introduce styles.

@Component({
  selector: "car-parts", // Display in selector defined in app.component.ts
  template: `
    <p>There are {{totalCarParts()}} total parts in stock.</p>
    <ul>
      <!-- carParts in an array object defined in AppComponent Class. -->
      <!-- carPart is a local variable. -->
      <li *ngFor="let carPart of carParts">
        <h2>{{carPart.name | uppercase}}</h2>
        <p class="description">{{carPart.description}}</p>
        <p class="price">{{carPart.price | currency:"EUR":true}}</p>
        <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
        <p *ngIf="carPart.inStock === 0">Out of stock</p>
      </li>
    </ul>
  `,
  styles: [`
    .description { 
      color: #ff0000;
      font-size: small;
    }
    .price{
      font-weight: bold;
    }
  `]
})

Here is out put.





















Can we have same CSS Class Name in different component in same page? Answer is Yes, because Angular scope the CSS Class. Confusing? Try to create same Class Name in different component in same page and view browser's source, you should understand.

Huh... Now we have JavaScript, HTML and CSS in same file. Is it messy and hard to maintenance when scale? Let's split our HTML and CSS into different file by using component decorator templateUrl and styleUrls. HTML will store in car-parts.component.html and CSS will store in car-parts.component.css.

car-parts.component.html
<p>There are {{totalCarParts()}} total parts in stock.</p>
<ul>
  <!-- carParts in an array object defined in AppComponent Class. -->
  <!-- carPart is a local variable. -->
  <li *ngFor="let carPart of carParts">
    <h2>{{carPart.name | uppercase}}</h2>
    <p class="description">{{carPart.description}}</p>
    <p class="price">{{carPart.price | currency:"EUR":true}}</p>
    <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
    <p *ngIf="carPart.inStock === 0">Out of stock</p>
  </li>
</ul>
car-parts.component.css
.description {
  color: #ff0000;
  font-size: small;
}

.price{
  font-weight: bold;
}
car-parts.component.ts
@Component({
  selector: "car-parts", // Display in selector defined in app.component.ts
  templateUrl: "app/car-parts.component.html",
  styleUrls: ["app/car-parts.component.css"]
})
Again, no new functionality, just splitting the files.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 3.1 - Splitting to Two Components (Exporting & Importing)

In part 3, we are going to split our code (Component, HTML, CSS, Model and Mock) into different files. Splitting our code into different file allow our code easy to maintain as well as easy to scale.

In this section, we are going to split our component into multiple files.
  • main.ts - where we'll bootstrap our application to load first component.
  • app.component.ts - This component contains our page header.
  • car-parts.component.ts - This component contains list of car parts.
Here is app.component.ts.
import {Component} from '@angular/core';

// This is component declarator, we called it metadata.
@Component({
  selector: "my-app",
  template: `
    <h1>{{title}}</h1>
    <car-parts></car-parts>
  `
})

export class AppComponent{
  title = "Ultra Racing"  // Example of property 
}
  • Added "export" in-front of class, so it can be import into main.ts.
  • Added custom selector "car-parts", this is to display our car parts using car-parts.component.ts.
Here is car-parts.component.ts.
import {Component} from '@angular/core'; @Component({   selector: "car-parts", // Display in selector defined in app.component.ts   template: ` <p>There are {{totalCarParts()}} total parts in stock.</p>     <ul>       <!-- carParts in an array object defined in AppComponent Class. -->       <!-- carPart is a local variable. -->       <li *ngFor="let carPart of carParts">         <h2>{{carPart.name | uppercase}}</h2>         <p>{{carPart.description}}</p>         <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>         <p *ngIf="carPart.inStock === 0">Out of stock</p>       </li>     </ul>   ` }) export class CarPartComponent { carParts = [{       "id":1,     "name":"Super Tires",     "description":"These tires are the very best",     "inStock":5   },   {     "id":2,     "name":"Reinforced shocks",     "description":"Shock made from krytonite",     "inStock":4   },   {     "id":3,     "name":"Padded Seats",     "description":"Super soft scats for a smooth ride.",     "inStock":0   }] // Example of object   
  totalCarParts(){     let sum = 0; for (let carPart of this.carParts) {   sum += carPart.inStock; } return sum; } }
Here is main.ts.
import {NgModule, Component} from '@angular/core';
import {AppComponent} from './app.component';
import {CarPartComponent} from './car-parts.component';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

@NgModule ({
  imports:      [ BrowserModule ], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent], // Import dependencies.
  bootstrap:    [ AppComponent ] // Indicate first component to launch.
})

class AppModule {}

// Start the application in web browser.
platformBrowserDynamic().bootstrapModule(AppModule);
  • Added import AppComponent and CarPartComponent.
  • Added CarPartComponent into NgModule's declarations.
In this section, I didn't add any new functionality, just split the component into different file.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 2.2 - Pipes & Methods

We use Pipes to transform data. A Pipes takes in data as input and transforms it to a desired output. Similar to Unix Pipe, if you are familiar with it.

Below example is to write car part names in capital letter.
@Component({
  selector: "my-app",
  template: `
    <h1>{{title}}</h1>
    <ul>
      <!-- carParts in an array object defined in AppComponent Class. -->
      <!-- carPart is a local variable. -->
      <li *ngFor="let carPart of carParts">
        <h2>{{carPart.name | uppercase}}</h2>
        <p>{{carPart.description}}</p>
        <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
        <p *ngIf="carPart.inStock === 0">Out of stock</p>
      </li>
    </ul>
  `
})
Here are the additional Pipes to use.
  • lowercase - Well, lowercase...
  • date - Format dates, how you like them...
  • number - Format numbers.
  • decimal - Format decimal.
  • replace - Create a new string, replacing specific character.
  • slide - Create a new list or string containing a subset of the element.
  • json - transform any input to a JSON formatted string.
  • * You also can create a custom pipe.
Next example is to add a total car part using method() - totalCarParts().

First create totalCarParts() method in AppComponent class.
class AppComponent{
  title = "Ultra Racing",  // Example of property
  carParts = [{ ... }], // Example of object
  totalCarParts(){
    let sum = 0;
    for (let carPart of this.carParts) {
      sum += carPart.inStock;
    }
    return sum;
  }
}
Second display total car parts in template.
@Component({
  selector: "my-app",
  template: `
    <h1>{{title}}</h1>
    <p>There are {{totalCarParts()}} total parts in stock.</p>
    <ul>
      ...
    </ul>
  `
})
Enter command "npm start" to run the application.




















Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 2.1 - Structure Directive

A directive (within Angular) is how we add dynamic behavior to HTML.

There are 3 different kinds of directives
  1. Component - Directive with a template.
  2. Structure - Alters layout by adding, removing or replacing DOM HTML elements. Example: ngFor and ngIf.
  3. Attribute - change the appearance or behavior of an element.
Below code is an example how we add a property and array object into Component and display in index.html using selector.
  • ngFor is structure directive. Loops through an array.
  • ngIf is another structure directive. It allows us to evaluate conditionals, show content conditionally.
@Component({
  selector: "my-app",
  template: `
    <h1>{{title}}</h1>
    <ul>
      <!-- carParts in an array object defined in AppComponent Class. -->
      <!-- carPart is a local variable. -->
      <li *ngFor="let carPart of carParts">
        <h2>{{carPart.name}}</h2>
        <p>{{carPart.description}}</p>
        <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
        <p *ngIf="carPart.inStock === 0">Out of stock</p>
      </li>
    </ul>
  `
})
class AppComponent{   title = "Ultra Racing",  // Example of property   carParts = [{       "id":1,     "name":"Super Tires",     "description":"These tires are the very best",     "inStock":5   },   {   "id":2, "name":"Reinforced shocks", "description":"Shock made from krytonite", "inStock":4 }, {     "id":3,     "name":"Padded Seats",     "description":"Super soft scats for a smooth ride.",     "inStock":0   }] // Example of object }
Enter command "npm start" to run the application.



















Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Friday, November 18, 2016

Angular 2 Part 1 - My First Component

Angular is a framework for dynamic web application. Angular has 2 versions and both version works very different. In this article, I am going talk about Angular 2.

Angular 2 can be written in JavaScript, TypeScript or DART. I am using TypeScript on all my examples.

TypeScript is Microsoft extension of JavaScript. It allows to add powerful type check and object-oriented features. TypeScript is superset of JavaScript and importantly, Angular 2 source is programmed with TypeScript.

Prerequisite on Angular 2 with TypeScript is to install npm. Because node.js installer come with npm, so we are using it to install npm. Take note that we don't code node.js.

npm is JavaScript package manager to share, reuse JavaScript. We use npm to download Angular 2 source files. To download and install Angular 2 with TypeScript, please follow the prerequisite in Angular 2 Quickstart page - https://angular.io/docs/ts/latest/quickstart.html#!#prereq.

You should have below folder structures after install Angular's sources.
- node_modules (folder to store Angular 2 source.)
- package.json (identifies npm package dependencies for the project)
- systemjs.config.js (defines how the TypeScript compiler generates JavaScript from the project's files.)
- tsconfig.json (provides information to a module loader about where to find application modules, and registers all the necessary packages.)

Now we going to create our first component.

First, we create index.html.
<html>
  <head>
    <!-- Angular 2 libraries -->
    <script>
      System.import('app')     // This piece is calling app/main.ts where we write our application code.
        .catch ( function(err){ console.error(err);} );     // We also include error checking.
    </script>
  <body>
    <!-- This custom tab is where Angular 2 application will load. -->
    <my-app>Loading...</my-app>
  </body>
  </head>
<html>
Second, we code Angular 2 on app/main.ts.
import {NgModule, Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

// This is component declarator, we called it metadata.
@Component ({
  selector: 'my-app',  // Custom tab in index.html that will load the component code.
  template: '<h1>Hello Angular 2!</h1>'  // HTML code going to load in selector.
})

class AppComponent { }

@NgModule ({
  imports:      [ BrowserModule ], // List down all component will be used.
  declarations: [ AppComponent ], // Import dependencies.
  bootstrap:    [ AppComponent ] // Indicate first component to launch.
})

class AppModule {}

// Start the application in web browser.
platformBrowserDynamic().bootstrapModule(AppModule);

Enter command "npm start" to run the application.







BrowserModule - Module needed for running angular Website.
platformBrowserDynamic  - Angular library needed to run the application.
NgModule - Group Angular code into blocks of functionally.
Component - Building block of Angular 2 Application and can be nested to one inside the other. Each component may have its own class file, html file and css file.

Follow the example, you should see Loading... then change to Hello Angular 2!.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts