Saturday, 30 April 2016

Angular Js - Lesson 9 - Forms_5 - customizing validators


Instance variable version of customized validated Control 



import { Component } from 'angular2/core';
import {
  ControlGroup,
  AbstractControl,
  FormBuilder,
  Validators,
  Control,
  CORE_DIRECTIVES,
  FORM_DIRECTIVES
} from 'angular2/common';

@Component({
  selector: 'demo-form-with-custom-validations',
  directives: [CORE_DIRECTIVES, FORM_DIRECTIVES],
  template: `
    <div class="ui raised segment">
      <h2 class="ui header">Demo Form: with custom validation</h2>
      <form [ngFormModel]="myForm"
            (ngSubmit)="onSubmit(myForm.value)"
            class="ui form">
        <div class="field"
             [class.error]="sku.touched && !sku.valid">
          <label for="skuInput">SKU</label>
          <input type="text"
                  id="skuInput"
                  placeholder="SKU"
                  [ngFormControl]="sku"]>
          <div *ngIf="!sku.valid" class="ui error message">SKU is invalid.</div>
          <div *ngIf="sku.hasError('required')" class="ui error message">
            SKU is required.
          </div>
          <div *ngIf="sku.hasError('invalidSku')" class="ui error message">
            SKU must begin with <tt>123</tt>
          </div>
        </div>
        <div *ngIf="!myForm.valid">
          Form is invalid.
        </div>
        <button type="submit" class="ui button">Submit</button>
      </form>
    </div>
  `
})
export class DemoFormWithCustomValidation{
  myForm: ControlGroup;
  sku: AbstractControl;
 
  /* Adding multiple validators to a single field requires using
  Validators.compose which takes an array of validators wrapping
  all of the validators and assigning it to a control. The control
  is not valid untill all the validations in the array are valid. */
  constructor(fb: FormBuilder){
    this.myForm = fb.group({
      'sku': ['', Validators.compose([
        Validators.required,
        skuValidator
      ])]
    });
   
    this.sku = this.myForm.controls['sku'];
  }//constructor ends here.
 
  onsubmit(value: string): void{
    console.log('You submitted value: ', value);
  }
}//class DemoFormWithCustomValidation ends here.

/* Custom validation. We are customizing validation using the  function
skuValidator given below. We want the sku to begin with numbers 123
so we will make sure in the funciton below that the sku begins with numbers.
 The function returns a StringMap<string, boolean> where the key is
 "error code" and the value is "true" if the validator fails.
 */
function skuValidator(control: Control): {[s: string]: boolean}{
  if(!control.value.match(/^123/)){
    return {invalidSku: true};
  }
}

Angular Js - Lesson 9 - Forms_4 - validators

Non-instance variable version of validated Control code

Creating an instance variable for every input tag on a form is verbose. In the code below we do not use sku: AbstractControl as we did in the previous example as we are not creating instance for an input tag in our form here. Since we are not exposing the sku control as an instance variable we have to get a reference to sku using myForm.find or ngFormControl directive. The method .find allows us to look up a child control by path so we can use it like this. myForm.find('sku').touched. Another way to get a reference to sku is via the ngForm export of the ngFormControl directive. ngFormControl exports itself as ngForm so we can use this export by using the #reference syntax like this. 
#sku = ngForm
But it should be kept in mind that sku is now an instance of ngFormControl directive
 and that sku is not a control. To get a reference to the control we do as sku.control as shown in the following line.
!sku.control.valid which checks if the related input control is valid. Similarly ku.control.touched checks if the related input control has been made dirty. 

Note that local references that we create using the #reference syntax are only available to sibling and children elements but not parents. The following code will not work because the <div class="field" is a parent of the input element that declares the reference.
<div class="field" [class.error]="!sku.control.valid && sku.control.touched">

Here is the complete code.

import { Component } from 'angular2/core';
import {
  ControlGroup,
  FormBuilder,
  Validators,
  CORE_DIRECTIVES,
  FORM_DIRECTIVES
} from 'angular2/common';

@Component({
  selector: 'demo-form-with-validations-shorthand',
  directives: [CORE_DIRECTIVES, FORM_DIRECTIVES],
  template: `
    <div class="ui raised segment">
      <h2 class="ui header">Demo Form: with validations (shorthand)</h2>
      <form [ngFormModel]="myForm"
            (ngSubmit)="onSubmit(myForm.value)"
            class="ui form">
        <div class="field"
              [class.error]="myForm.find('sku').touched && !myForm.find('sku').valid">
          <label for="skuInput">
            SKU
          </label>
          <input type="text"
                 id="skuInput"
                 placeholder="SKU"
                 #sku="ngForm"
                 [ngFormControl]="myForm.controls['sku']">
            <div *ngIf="!sku.control.valid"
                 class="ui error message">
              SKU is invalid.
            </div>
            <div *ngIf="sku.control.hasError('required')"
                  class="ui error message">
              SKU is required.
            </div>    
        </div>
        <div *ngIf="!myForm.valid"
              class="ui error message">
          Form is invalid.
        </div>
        
        <button type="submit" class="ui button">
          Submit
        </button>
      </form>    
    </div>
  `
})
export class DemoFormValidationsShorthand{
  myForm: ControlGroup;
  
  constructor(fb: FormBuilder){
    this.myForm = fb.group({
      'sku': ['', Validators.required]
    });
  }//constructor ends here.
  
  onSubmit(value: any){
    console.log('You submitted value: ', value.sku);
  }
}//class DemoFormValidationsShorthand ends here.

Friday, 29 April 2016

Angular Js - Lesson 9 - Forms_3 - validators

Validators in Angular Js 2



/*
Validators to validate the form controls.
Using FormBuilder in this example.
We are using just one input field in this form.
Explicitly setting the sku Contorl as an instance variable in the controller. This is the
most flexible way to deal with individual controls in the view as we set up an instance
variable for each control in the class in which we define this component.
 */
import { Component } from 'angular2/core';
import {
  ControlGroup,
  AbstractControl,
  FormBuilder,
  Validators,
  FORM_DIRECTIVES,
  CORE_DIRECTIVES
} from 'angular2/common';

@Component({
  selector: 'demo-form-with-validations-explicit',
  directives: [CORE_DIRECTIVES, FORM_DIRECTIVES],
  template: `
    <div class:"ui raised segement">
      <h2 class:"ui header">Demo Form: with validations (explicit)</h2>
     
      <form [ngFormModel]="myForm"
            (ngSubmit)="onSubmit(myForm.value)"
            class="ui form">
            <!--
              We are using Semantic UI CSS Framework's CSS class .error which means
              if we add the class error to the <div class="field"> it will show the
              input tag with a red border.
              .touched below means  that we only want to show the error if the user
              has tried editing the form. .valid below means that the control is
              invalid now.
            -->
        <div class="field"
             [class.error]="sku.touched && !sku.valid">
          <label for="skuInput">SKU</label>
          <input type="text"
                 id="skuInput"
                 placeholder="sku"
                 [ngFormControl]="sku">
            <div *ngIf="!sku.valid" class="ui error message">
              SKU is invalid.
            </div>
            <div *ngIf="sku.hasError('required')" class="ui error message">
              SKU is required.
            </div>
        </div>
            <div *ngIf="!myForm.valid" class="ui error message">
              Form is invalid.
            </div>
           
            <button type="submit" class="ui button">Submit</button>    
     </form>
    </div>
  `
})

export class DemoFormWithValidationsExplicit{
  myForm: ControlGroup;
  /* There are two ways we can access the validation value in the view:
  1. We can explicitly assign the Control sku to an instance variable of the class and
  this gives easy access to the Control in the view. This is what we are doing in
  this example. The kickback of this method is that we have to creat n number of
  instance variable for n controls.
  Another way is to lookup the Control sku from myForm in the view. This requires
  less work in the Component definiton class but is slightly more verbose in the view.
   */
  sku: AbstractControl;
  /* During injection an instance of FormBuilder will be created and we assign that
  instance to the local variable fb in the arguments to the constructor. */
  constructor(fb: FormBuilder){
    /* We create a ControlGroup by calling method fb.group() which takes an object
    of key-value pairs that specify the controls in this group. */
    this.myForm = fb.group({
      /* We are using FormBuilder therefore, we will using the following syntax.
      Otherwise to assign a validator to a Control object we can simply pass the validator
      to the constructor of that control as given below:
      let control = new Control('sku', Validators.required);
       */
      'sku': ['', Validators.required]
    });
    this.sku = this.myForm.controls['sku'];
  }//constructor ends here.
 
  onSubmit(value: string): void{
    console.log('You submitted value: ', value);
  }
 
}//class DemoFormWithValidationsExplicit ends here.


Thursday, 28 April 2016

Angular Js - Lesson 9 - Forms_1

Angular Js Forms - part 1




Here is the code for the form above.

import { Component } from 'angular2/core';
import { FORM_DIRECTIVES } from 'angular2/common';
/* FORM_DIRECTIVES is a constant that Angular provides for us as a shorthand
to several driectives that are all useful in a form.
FORM_DIRECTIVES includes:
ngControl
ngControlGroup
ngForm
ngModel
....... and many more.
By injecting FORM_DIRECTIVES we can use any of the directives in that list in our view template. */

@Component({
  selector: 'demo-form-sku',
  directives: [FORM_DIRECTIVES],
  /* Since we have injected FORM_DIRECTIVES, therefore, that makes
  ngForm available to our view and will get attached to any
  element that matches their selector. In the template below
  bgForm directive gets automatically attached to the <form> tag
  in the view. This happens behid the scenes.
  */
  /* ngForm gives us two important pieces of functionalities:
  (a). A ControlGroup named ngForm.
  (b). An output (ngSubmit) which we use in our form to call the
  method onSubmit(f.value)
  */
  /* SKU is an abbreviation for Stock Keeping Unit. */
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: Sku</h2>
    <form #f="ngForm"
          (ngSubmit)="onSubmit(f.value)"
          class="ui form">

      <div class="field">
        <label for="skuInput">SKU</label>
        <input type="text"
               id="skuInput"
               placeholder="SKU"
               ngControl="sku">
      </div>

      <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})
export class DemoFormSku {
  onSubmit(form: any): void {
    console.log('you submitted value:', form);
  }
}

Angular Js - Lesson 9 - Forms_2

Angualr Js - Forms part 2 - using ngFormmodel and ngFormControl

To create a new ControlGroup and Controls implicitly use:
ngForm and ngControl.

To bind an already existing ControlGroup and Controls use ngFormModel and ngFormControl.



import { Component } from 'angular2/core';
import {
  FORM_DIRECTIVES,
  FormBuilder,
  ControlGroup
} from 'angular2/common';

@Component({
  selector: 'demo-form-sku-builder',
  directives: [FORM_DIRECTIVES],
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: Sku with Builder</h2>
    <!--
    The component ngForm is applied for us automatically when we use FORM_DIRECTIVES
    and this ngForm creates its own ControlGroup. But here we do not want to use any
    outside ControlGroup. Instead we want to use our instance varibale myForm which
    we created with our FormBuilder. To do this Angular gives us another directive
    that can be used when we have an existing ControlGroup. This directive is called
    ngFormModel. In the line <form [ngFormModel]="myForm" we are telling Angular
    that we want to use myForm as the ControlGroup for this form.
    -->
    <form [ngFormModel]="myForm"
          (ngSubmit)="onSubmit(myForm.value)"
          class="ui form">

      <div class="field">
        <label for="skuInput">SKU</label>
        <input type="text"
               id="skuInput"
               placeholder="SKU"
               <!-- When we want to bind an existing control to an input we use NgFormControl. -->
               [ngFormControl]="myForm.controls['sku']">
      </div>

    <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})
export class DemoFormSkuBuilder {
  myForm: ControlGroup;
  /* During injection an instance of FormBuilder will be created
  and we assign that instance to the local variable fb in the line below.
   */
  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      /* We create a ControlGroup by calling method fb.group() which
      takes an object of key-value paris that specify the controls in this group.
       */
      'sku': ['ABC123']
      /* We are setting up one control sku and also setting its default value to ABC123.
      We are using an array in the line above so that we could later on
      add more configuration options here.
       */
    });
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}

/***********************************************************************/


Tuesday, 26 April 2016

Angular Js - Lesson 8

Angular Js 2 built-in components - ngStyle built-in component

import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';

@Component({
  selector: 'style-sample-app',
  template: `
    <h4 class="ui horizontal divider header">
      style.background-color
    </h4>

    <div [style.background-color]="'yellow'">
      Uses fixed yellow background
    </div>

    <h4 class="ui horizontal divider header">
      ngStyle literal
    </h4>

    <div [ngStyle]="{color: 'white', 'background-color': 'blue'}">
      Uses fixed white text on blue background
    </div>

    <h4 class="ui horizontal divider header">
      ngStyle literal and style.font-size.px
    </h4>

    <div>
      <span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize">
        red text
      </span>
    </div>

    <h4 class="ui horizontal divider header">
      ngStyle with an object
    </h4>

    <div [ngStyle]="style"></div>

    <h4 class="ui horizontal divider header">
      ngStyle with object property from variable
    </h4>

    <div>
      <span [ngStyle]="{color: colorinput.value}">
        {{ colorinput.value }} text
      </span>
    </div>

    <h4 class="ui horizontal divider header">
      style from variable
    </h4>

    <div [style.background-color]="colorinput.value"
         style="color: white;">
      {{ colorinput.value }} background
    </div>

    <h4 class="ui horizontal divider header">
      Play with the color and font-size here
    </h4>

    <div class="ui input">
      <input type="text" name="color" value="{{color}}" #colorinput>
    </div>

    <div class="ui input">
      <input type="text" name="fontSize" value="{{fontSize}}" #fontinput>
    </div>

    <button class="ui primary button" (click)="apply(colorinput.value, fontinput.value)">
      Apply settings
    </button>
  `
})
class StyleSampleApp {
  color: string;
  fontSize: number;
  style: {
    'background-color': string,
    'border-radius': string,
    border?: string,
    width?: string,
    height?: string
  };

  constructor() {
    this.fontSize = 16;
    this.color = "blue";
    this.style = {
      'background-color': '#ccc',
      'border-radius': '50px',
      'height': '30px',
      'width': '30px',
    };
  }//constructor ends here.

  apply(color, fontSize) {
    this.color = color;
    this.fontSize = fontSize;
  }

}//class StyleSampleApp ends here.

bootstrap(StyleSampleApp);
/*********************************************************************/

The css file styles.css has the following code.

body {
  font-family: verdana, arial, helvetica, sans-serif;
}

div {
  padding: 3px;
  margin: 2px;
}

.ui.menu .item img.logo {
    margin-right: 1.5em;
}

/*********************************************************************/

The index.html has the following code.

<!doctype html>
<html>
  <head>
    <title>Angular 2 - ngStyle demo</title>
    <link rel="icon" type="image/png" href="resources/images/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" href="resources/images/favicon.ico" />
    <!-- Libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- Stylesheet -->
    <link rel="stylesheet" type="text/css" href="resources/vendor/semantic.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>

    <!-- Configure System.js, our module loader -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app.js')
            .then(null, console.error.bind(console));
    </script>

    <!-- Menu Bar -->
    <div class="ui menu">
      <div class="ui container">
        <a href="#" class="header item">
          <img class="logo" src="resources/images/ng-book-2-minibook.png">
          ng-book 2
        </a>
        <div class="header item borderless">
          <h1 class="ui header">
            Angular 2 ngStyle demo
          </h1>
        </div>
      </div>
    </div>

    <div class="ui main text container">
      <style-sample-app></style-sample-app> <!-- Our app loads here -->
    </div>

  </body>
</html>

/*********************************************************************/

Angular Js - Lesson 7

Angular Js 2 built-in components - built-in component app demo

import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';

@Component({
  selector: 'ng-non-bindable-sample-app',
  template: `
  <div>
    <span class="bordered">{{ content }}</span>
    <span class="pre" ngNonBindable>
      &larr; This is what {{ content }} rendered
    </span>
  </div>
  `
})
class NgNonBindableSampleApp {
  content: string;

  constructor() {
    this.content = 'Some text';
  }
}

bootstrap(NgNonBindableSampleApp);

/*******************************************************************/

The styles.css file used has the following code.


.bordered {
  border: 1px dashed black;
  background-color: #eee;
  padding: 10px;
}

.pre {
  font-family: monospace;
}

.ui.menu .item img.logo {
    margin-right: 1.5em;
}

/*******************************************************************/

The index.html has the following code.


<!doctype html>
<html>
  <head>
    <title>Angular 2 - ngNonBindable demo</title>
    <link rel="icon" type="image/png" href="resources/images/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" href="resources/images/favicon.ico" />
    <!-- Libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- Stylesheet -->
    <link rel="stylesheet" type="text/css" href="resources/vendor/semantic.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>

    <!-- Configure System.js, our module loader -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app.js')
            .then(null, console.error.bind(console));
    </script>

    <!-- Menu Bar -->
    <div class="ui menu">
      <div class="ui container">
        <a href="#" class="header item">
          <img class="logo" src="resources/images/ng-book-2-minibook.png">
          ng-book 2
        </a>
        <div class="header item borderless">
          <h1 class="ui header">
            Angular 2 ngNonBindable demo
          </h1>
        </div>
      </div>
    </div>

    <div class="ui main text container">
      <ng-non-bindable-sample-app></ng-non-bindable-sample-app> <!-- Our app loads here -->
    </div>

  </body>
</html>


/*******************************************************************/

Angular Js - Lesson 6


Angular Js 2 - Built-in components - ngSwitch component app demo

In the code below we demonstrate how the built-in ngSwitch component can be used to show those list items that we want to show based on the value of the variable choice in the ngSwitch. Note that when he value of choice variable is 2 then two list items are shown, i.e "Second choice" and "Second choice, again" as both the list items use the same condition *ngSwitchWhen="2". We also use *ngSwitchDefault to show how to use the "else" case in an if-else structure. We can use ngSwitch built-in component without the default case if we want to.

import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';

@Component({
  selector: 'switch-sample-app',
  template: `
    <h4 class="ui horizontal divider header">
      Current choice is {{ choice }}
    </h4>

    <div class="ui raised segment">
      <ul [ngSwitch]="choice">
        <li *ngSwitchWhen="1">First choice</li>
        <li *ngSwitchWhen="2">Second choice</li>
        <li *ngSwitchWhen="3">Third choice</li>
        <li *ngSwitchWhen="4">Fourth choice</li>
        <li *ngSwitchWhen="2">Second choice, again</li>
        <li *ngSwitchDefault>Default choice</li>
      </ul>
    </div>

    <div style="margin-top: 20px;">
      <button class="ui primary button" (click)="nextChoice()">
        Next choice
      </button>
    </div>
  `
})
class SwitchSampleApp {
  choice: number;

  constructor() {
    this.choice = 1;
  }

  nextChoice() {
    this.choice += 1;

    if (this.choice > 5) {
      this.choice = 1;
    }
  }
}

bootstrap(SwitchSampleApp);
/******************************************************************************/

The index.html is given below:

<!doctype html>
<html>
  <head>
    <title>Angular 2 - ngSwitch demo</title>
    <link rel="icon" type="image/png" href="resources/images/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" href="resources/images/favicon.ico" />
    <!-- Libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- Stylesheet -->
    <link rel="stylesheet" type="text/css" href="resources/vendor/semantic.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>

    <!-- Configure System.js, our module loader -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app.js')
            .then(null, console.error.bind(console));
    </script>

    <!-- Menu Bar -->
    <div class="ui menu">
      <div class="ui container">
        <a href="#" class="header item">
          <img class="logo" src="resources/images/ng-book-2-minibook.png">
          ng-book 2
        </a>
        <div class="header item borderless">
          <h1 class="ui header">
            Angular 2 ngSwitch demo
          </h1>
        </div>
      </div>
    </div>

    <div class="ui main text container">

      <switch-sample-app></switch-sample-app> <!-- Our app loads here -->

    </div>

  </body>
</html>

/******************************************************************************/

The file styles.css has the following code:


body {
  font-family: verdana, arial, helvetica, sans-serif;
}

div {
  padding: 3px;
  margin: 2px;
}

.ui.menu .item img.logo {
    margin-right: 1.5em;
}

/******************************************************************************/


Angular Js - Lesson 5

Angular Js Built-in components - ngFor component demo app


In this app we are going to demonstrate the use of repetitive structure which Angular 2 provides as a built-in component so that we can use it in our components.

/* Angular 2 built-in components - ngFor demo app */
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';

@Component({
  selector: 'ng-for-sample-app',
  template: `
  <h4 class="ui horizontal divider header">
    Simple list of strings
  </h4>

  <div class="ui list" *ngFor="#c of cities">
    <div class="item">{{ c }}</div>
  </div>

  <h4 class="ui horizontal divider header">
    List of objects
  </h4>

  <table class="ui celled table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>City</th>
      </tr>
    </thead>
    <tr *ngFor="#p of people">
      <td>{{ p.name }}</td>
      <td>{{ p.age }}</td>
      <td>{{ p.city }}</td>
    </tr>
  </table>

  <h4 class="ui horizontal divider header">
    Nested data
  </h4>

  <div *ngFor="#item of peopleByCity">
    <h2 class="ui header">{{ item.city }}</h2>

    <table class="ui celled table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tr *ngFor="#p of item.people">
        <td>{{ p.name }}</td>
        <td>{{ p.age }}</td>
      </tr>
    </table>
  </div>

  <h4 class="ui horizontal divider header">
    List with index
  </h4>

  <div class="ui list" *ngFor="#c of cities; #num = index">
    <div class="item">{{ num+1 }} - {{ c }}</div>
  </div>
  `
})
class NgForSampleApp {
  cities: Array<string>;
  people: Array<Object>;
  peopleByCity: Object;

  constructor() {
 
    this.cities = ['Miami', 'Sao Paulo', 'New York'];
 
    this.people = [
      { name: 'Anderson', age: 35, city: 'Sao Paulo' },
      { name: 'John', age: 12, city: 'Miami' },
      { name: 'Peter', age: 22, city: 'New York' }
    ];
 
    this.peopleByCity = [
      {
          city: 'Miami',
          people: [
              { name: 'John', age: 12 },
              { name: 'Angel', age: 22 }
          ]
      },
      {
          city: 'Sao Paulo',
          people: [
              { name: 'Anderson', age: 35 },
              { name: 'Felipe', age: 36 }
          ]
      }
    ];
 
  };//constructor ends here.

}//class NgForSampleApp ends here.

bootstrap(NgForSampleApp);

/******************************************************************************/

The code for index.html is here:

<!doctype html>
<html>
  <head>
    <title>Angular 2 - ngFor demo</title>
    <link rel="icon" type="image/png" href="resources/images/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" href="resources/images/favicon.ico" />
    <!-- Libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- Stylesheet -->
    <link rel="stylesheet" type="text/css" href="resources/vendor/semantic.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>

    <!-- Configure System.js, our module loader -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app.js')
            .then(null, console.error.bind(console));
    </script>

    <!-- Menu Bar -->
    <div class="ui menu">
      <div class="ui container">
        <a href="#" class="header item">
          <img class="logo" src="resources/images/ng-book-2-minibook.png">
          ng-book 2
        </a>
        <div class="header item borderless">
          <h1 class="ui header">
            Angular 2 ngFor demo
          </h1>
        </div>
      </div>
    </div>

    <div class="ui main text container">
      <ng-for-sample-app></ng-for-sample-app> <!-- Our app loads here -->
    </div>

  </body>
</html>

/******************************************************************************/


Angular Js - Lesson 4

Angular2 Built in components - ngClass demo app

In this app we display how do we use the built in component ngClass in Angular 2.

/* Angular2 ngClass demo */

import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';

@Component({
  selector: 'style-sample-app',
  template: `
  <div [ngClass]="{bordered: false}">This is never bordered</div>
  <div [ngClass]="{bordered: true}">This is always bordered</div>

  <div [ngClass]="{bordered: isBordered}">
   Using object literal. Border {{ isBordered ? "ON" : "OFF" }}
  </div>

  <div [ngClass]="classesObj">
    Using object var. Border {{ classesObj.bordered ? "ON" : "OFF" }}
  </div>

  <button (click)="toggleBorder()">Toggle</button>

  <div class="selectors">
    <div>
      <input type="checkbox"
             [checked]="classList.indexOf('blue') > -1"
             (click)="toggleClass('blue')">
      <span>Blue</span>
    </div>

    <div>
      <input type="checkbox"
             [checked]="classList.indexOf('round') > -1"
             (click)="toggleClass('round')">
      <span>Round</span>
    </div>
  </div>

  <div class="base" [ngClass]="['blue', 'round']">
    This will always have a blue background and
    round corners
  </div>

  <div class="base" [ngClass]="classList">
    This is {{ classList.indexOf('blue') > -1 ? "" : "NOT" }} blue
    and {{ classList.indexOf('round') > -1 ? "" : "NOT" }} round
  </div>
  `
})
class ClassSampleApp {
  isBordered: boolean;
  classesObj: Object;
  classList: Array<string>;

  constructor() {
    this.isBordered = true;
    this.classList = ['blue', 'round'];
    this.toggleBorder();
  }

  toggleBorder() {
    this.isBordered = !this.isBordered;
    this.classesObj = {
      bordered: this.isBordered
    };
  }

  toggleClass(cssClass) {
    var pos = this.classList.indexOf(cssClass);
    if (pos > -1) {
      /* Index returned is greater than -1 so the cssClass is found in classList.
      Remove the cssClass from the array classList.
      pos has the index of the element to be removed from the array pointed by classList.
      1 means remove one element from the array starting from index pos.
      */
      this.classList.splice(pos, 1);
    } else {
      /* Insert the cssClass in the array classList */
      this.classList.push(cssClass)
    }
  }
}

bootstrap(ClassSampleApp);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

The css used in this app is here. styles.css

body {
  font-family: verdana, arial, helvetica, sans-serif;
}

div {
  padding: 3px;
  margin: 2px;
}

button {
  margin-bottom: 20px;
}

.bordered {
  border: 1px dashed black;
  background-color: #eee;
}

.selectors {
  width: 200px;
  padding: 10px;
  border: 1px solid black;
  margin-bottom: 10px;
}

.base {
  padding: 10px;
  border: 1px solid #ccc;
}

.blue {
  color: white;
  background-color: blue;
}

.round {
  border-radius: 20px;
}

.ui.menu .item img.logo {
    margin-right: 1.5em;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

The index.html file used in this app is here. 

<!doctype html>
<html>
  <head>
    <title>Angular 2 - ngClass demo</title>
    <link rel="icon" type="image/png" href="resources/images/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" href="resources/images/favicon.ico" />
    <!-- Libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- Stylesheet -->
    <link rel="stylesheet" type="text/css" href="resources/vendor/semantic.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>

    <!-- Configure System.js, our module loader -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app.js')
            .then(null, console.error.bind(console));
    </script>

    <!-- Menu Bar -->
    <div class="ui menu">
      <div class="ui container">
        <a href="#" class="header item">
          <img class="logo" src="resources/images/ng-book-2-minibook.png">
          ng-book 2
        </a>
        <div class="header item borderless">
          <h1 class="ui header">
            Angular 2 ngClass demo
          </h1>
        </div>
      </div>
    </div>

    <div class="ui main text container">
      <style-sample-app></style-sample-app> <!-- Our app loads here -->
    </div>

  </body>
</html>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

After clicking the Toggle button and the two checkboxes we have:

Angular Js - Lesson 3

Inventory Displayer app.

This app shows list of products on the inventory of a store. Every product is shown in one row. A product is represented by a component namely Product. A ProductRow component is composed of three different component, namely ProductImage,  ProductDepartment, and PriceDisplay.

We use component ProductList for rendering all ProductRows and for storing the currently selected Product. InventoryApp component uses component ProductList to display the whole list of product available. The model part in the MVC pattern is for the time being inside the component inventory-app as we are creating products inside the constructor in the controller/class of the component inventory-app.

Here is the code for the app.ts file:

import { Component, EventEmitter } from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

class Product {
  constructor(
    public sku: string,
    public name: string,
    public imageUrl: string,
    public department: string[],
    public price: number) {
  }
}
/***************************************************************************************/
@Component({
  selector: 'product-image',
  host: {class: 'ui small image'},
  inputs: ['product'],
  template: `
  <img class="product-image" [src]="product.imageUrl">
  `
})
class ProductImage {
  product: Product;
}
/***************************************************************************************/
@Component({
  selector: 'product-department',
  inputs: ['product'],
  template: `
  <div class="product-department">
    <span *ngFor="#name of product.department; #i=index">
      <a href="#">{{ name }}</a>
      <span>{{i < (product.department.length-1) ? '>' : ''}}</span>
    </span>
  </div>
  `
})
class ProductDepartment {
  product: Product;
}
/***************************************************************************************/
@Component({
  selector: 'price-display',
  inputs: ['price'],
  template: `
  <div class="price-display">\${{ price }}</div>
  `
})
class PriceDisplay {
  price: number;
}
/***************************************************************************************/
@Component({
  selector: 'product-row',
  inputs: ['product'],
  host: {'class': 'item'},
  directives: [ProductImage, ProductDepartment, PriceDisplay],
  template: `
  <product-image [product]="product"></product-image>
  <div class="content">
    <div class="header">{{ product.name }}</div>
    <div class="meta">
      <div class="product-sku">SKU #{{ product.sku }}</div>
    </div>
    <div class="description">
      <product-department [product]="product"></product-department>
    </div>
  </div>
  <price-display [price]="product.price"></price-display>
  `
})
class ProductRow {
  product: Product;
}
/***************************************************************************************/
/**
 * @ProductsList: A component for rendering all ProductRows and
 * storing the currently selected Product
 */
@Component({
  selector: 'products-list',
  directives: [ProductRow],
  inputs: ['productList'],
  outputs: ['onProductSelected'],
  template: `
  <div class="ui items">
    <product-row
      *ngFor="#myProduct of productList"
      [product]="myProduct"
      (click)='clicked(myProduct)'
      [class.selected]="isSelected(myProduct)">
    </product-row>
  </div>
  `
})
class ProductsList {
  productList: Product[];
  onProductSelected: EventEmitter<Product>;
  currentProduct: Product;

  constructor() {
    this.onProductSelected = new EventEmitter();
  }

  clicked(product: Product): void {
    this.currentProduct = product;
    this.onProductSelected.emit(product);
  }

  isSelected(product: Product): boolean {
    if (!product || !this.currentProduct) {
      return false;
    }
    /* return true if the product passed as parameter to this method is the same as pointed by currentProduct i.e., clicked by user. Otherwise return false.*/
    return product.sku === this.currentProduct.sku;
  }

}//class ProductList ends here.
/***************************************************************************************/
@Component({
  selector: 'inventory-app',
  directives: [ProductsList],/* This component will use product-list component and the name of the controller/class of that component is ProductList. */
 /* The view in the MVC pattern begins below. */
  template: `
  <div class="inventory-app">
    <products-list
      [productList]="products"
      (onProductSelected)="productWasSelected($event)">
    </products-list>
  </div>
  `
})
/* The controller (in the MVC pattern) for the component begins here. */
class InventoryApp {
  products: Product[];

  constructor() {
    /* Here is the Model in the MVC pattern. */
    this.products = [
      new Product(
        'MYSHOES', 'Black Running Shoes',
        '/resources/images/products/black-shoes.jpg',
        ['Men', 'Shoes', 'Running Shoes'],
        109.99),
      new Product(
        'NEATOJACKET', 'Blue Jacket',
        '/resources/images/products/blue-jacket.jpg',
        ['Women', 'Apparel', 'Jackets & Vests'],
        238.99),
      new Product(
        'NICEHAT', 'A Nice Black Hat',
        '/resources/images/products/black-hat.jpg',
        ['Men', 'Accessories', 'Hats'],
        29.99)
      ];
  }

  productWasSelected(product: Product): void {
    console.log('Product clicked: ', product);
  }
}//class InventoryApp ends here.
/***************************************************************************************/
bootstrap(InventoryApp);

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


Here is the index.html file:

<!doctype html>
<html>
  <head>
    <title>ng-book 2: Inventory App</title>
    <link rel="icon" type="image/png" href="resources/images/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" href="resources/images/favicon.ico" />
    <!-- Libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- Stylesheet -->
    <link rel="stylesheet" type="text/css" href="resources/vendor/semantic.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>

    <!-- Configure System.js, our module loader -->
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app.js')
            .then(null, console.error.bind(console));
    </script>

    <!-- Menu Bar -->
    <div class="ui menu">
      <div class="ui container">
        <a href="#" class="header item">
          <img class="logo" src="resources/images/ng-book-2-minibook.png">
          ng-book 2
        </a>
        <div class="header item borderless">
          <h1 class="ui header">
            Angular 2 Inventory App
          </h1>
        </div>
      </div>
    </div>

    <div class="ui main text container">
      <inventory-app></inventory-app> <!-- <--- Our app loads here! -->
    </div>

  </body>
</html>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


Here is the css used in the app. styles.css


.ui.menu .item img.logo {
    margin-right: 1.5em;
}


.ui.items>.item {
  border: 1px solid rgba(255, 255, 255, 0.0);
  border-radius: 5px;
}

.ui.items>.item.selected {
  border: 1px solid rgba(163, 51, 200, 0.41);
  border-radius: 5px;
}

.ui.items>.item>.content>.header {
    padding-top: 1em;
}

.products-list {
  border-top: 1px solid black;
  border-left: 1px solid black;
  border-right: 1px solid black;
}

.product-row {
  border-bottom: 1px solid black;
}

.product-image {
  float: left;
}

.product-info {
  padding: 30px;
  float: left;
}

.price-display {
  padding: 30px;
  float: right;
}

.product-image {
  width: 100px;
  height: 100px;
  padding: 20px;
}

.cf:before,
.cf:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.cf:after {
    clear: both;
}

cf {
    *zoom: 1;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Wednesday, 20 April 2016

Angular Js - lesson 2

/*
A Single Page Application (SPA) which the user uses to post a new link of some website with a title and other users can vote on any link to show its ratings. The number of votes determine which website should be on shown higher than other websites. There are three components which are coded in the file app.ts and their names are given below:
1. Article
2. ArticleComponent
3. RedditApp

There is one html page namely index.html which shows the list of the articles along with their voting and buttons for voting up or voting down an article. Moreover, there are two text boxes where a user can enter a new title and a new link to be added to the list of articled after the user has clicked on a button that is used for adding new article to the collection of articles.
*/

/*app.ts*/

/// <reference path="node_modules/angular2/ts/typings/node/node.d.ts"/>
/// <reference path="node_modules/angular2/typings/browser.d.ts"/>

import { bootstrap } from 'angular2/platform/browser';
import { Component } from 'angular2/core';

@Component({
    selector: 'reddit-article',
    inputs: ['article'],
    host:{
        class: 'row'
    },
    template: `
        <div class="four wide column center aligned votes">
            <div class="ui statistic">
                <div class="value">
                    {{ article.votes }}
                </div>
                <div class="label">
                    Points
                </div>
            </div>
        </div>
        <div class="twelve wide column">
            <a class="ui large header" href="{{ article.link }}">
                {{ article.title }}
            </a>
            <div class="meta">
                ({{ article.domain() }})
            </div>
            <ul class="ui big horizontal list voters">
                <li class="item">
                    <a href (click)="voteUp()">
                        <i class="arrow up icon"></i>
                        upvote
                    </a>
                </li>
                <li class="item">
                    <a href (click)="voteDown()">
                        <i class="arrow down icon"></i>
                        downvote
                    </a>
                </li>
            </ul>
        </div>
    `
})

class ArticleComponent{
    article: Article;
 
    voteUp(): boolean{
        this.article.voteUp();
        return false;
    }
 
    voteDown(): boolean{
        this.article.voteDown();
        return false;
    }
}


class Article{
    title: string;
    link: string;
    votes: number;
 
    constructor(title: string, link:string, votes?:number){
        this.title = title;
        this.link = link;
        this.votes = votes || 0;
    }  
 
    voteUp(): void {
        this.votes += 1;
    }
 
    voteDown(): void {
        this.votes -= 1;
    }
    domain(): string{
        try {
            /* split() method returns an array and we assign the element at index [1] of that array to local constant link below.*/
            const link: string = this.link.split('//')[1];
             /* split() method returns an array and we assign the element at index [0] of that array to local constant link below.*/
            return link.split('/')[0];
        } catch (err) {
            return null;
        }
    }
}

@Component({
    selector: 'reddit',
    directives: [ArticleComponent],
    template: `
        <form class="ui large form segment">
            <h3 class="ui header">Add a Link</h3>
            <div class="field">
                <label for="title">Title:</label>
                <input name="title" #newtitle>
            </div>
            <div class="field">
                <label for="link">Link:</label>
                <input name="link" #newlink>
            </div>
         
            <button (click)="addArticle(newtitle, newlink)"
                class="ui positive right floated button">
                Submit link
            </button>
</form>

<div class="ui grid posts">
    <reddit-article *ngFor="#someArticle of sortedArticles()"
                        [article]="someArticle">
    </reddit-article>
</div>
    `
})
class RedditApp{
    articles: Article[];
    /*We can write the above as below also:
    articles : Array<Article>
    This is called generics. The array will contain elements of type Article.
    */
    constructor(){
        this.articles = [
            new Article('Anuglar 2', 'http://angular.io', 10),
            new Article('Fullstack', 'http://fullstack.io', 8),
            new Article('Angular Homepage', 'http://angular.io', 6),
        ];
    }
 
    addArticle(title: HTMLInputElement, link: HTMLInputElement): void{
        console.log(`Adding article title: ${title.value} and link:${link.value}`);
        this.articles.push(new Article(title.value, link.value, 0));//0 stands for number of votes.
        //Clearing the input field values.
        title.value = '';
        link.value = '';
    }
 
    sortedArticles(): Article[]{
        return this.articles.sort(
            (a: Article, b: Article) => b.votes - a.votes
        );
    }
}

bootstrap(RedditApp);

/****************************************************************************/
/* index.html */
<!doctype html>
<html>
  <head>
    <title>Angular 2 - Simple Reddit</title>
    <link rel="icon" type="image/png" href="resources/images/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" href="resources/images/favicon.ico" />
    <!-- Libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- Stylesheet -->
    <link rel="stylesheet" type="text/css" href="resources/vendor/semantic.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>

    <!-- Configure System.js, our module loader -->
    <script>
      System.config({
        packages: {      
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app.js')
            .then(null, console.error.bind(console));
    </script>

    <!-- Menu Bar -->
    <div class="ui menu">
      <div class="ui container">
        <a href="#" class="header item">
          <img class="logo" src="resources/images/ng-book-2-minibook.png">
          ng-book 2
        </a>
        <div class="header item borderless">
          <h1 class="ui header">
            Angular 2 Simple Reddit
          </h1>
        </div>
      </div>
    </div>

    <div class="ui main text container">
      <reddit></reddit> <!-- <--- Our app loads here! -->
    </div>

  </body>
</html>


/****************************************************************************/
/*styles.css*/
.ui.menu .item img.logo {
    margin-right: 1.5em;
}

form.ui.segment.form {
  background-color: #F1F9FF;
  margin-top: 2em;
}

form.form:after {
  content: '';
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

.votes {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #E6E6E6;
  padding: 1em 0;
  border-radius: 5px;
}

.ui.grid.posts {
  margin-top: 2em;
}

.meta {
  color: #9A9A9A
}

.ui.grid>.row>.column.votes {
  display: flex;
}

ul.ui.list li:before {
  content: '';
}

/****************************************************************************/
/*tsconfig.json*/
{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "files": [
    "app.ts",
    "node_modules/angular2/ts/typings/node/node.d.ts",
    "node_modules/angular2/typings/browser.d.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}
/****************************************************************************/

Angular Js - lesson 1

/*app.ts*/

/// <reference path="node_modules/angular2/ts/typings/node/node.d.ts"/>
/// <reference path="node_modules/angular2/typings/browser.d.ts"/>
import { bootstrap } from "angular2/platform/browser";
import { Component } from "angular2/core";

@Component({
  selector: 'hello-world',
  template: `
  <div>
    Hello world
  </div>
  `
})
class HelloWorld {
}

bootstrap(HelloWorld);

/*********************************************************************************/
/*tsconfig.json*/
{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules"
  ]
}

/*********************************************************************************/
/*index.html*/
<!doctype html>
<html>
  <head>
    <title>First App - Hello world</title>
    <!-- Libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- Stylesheet -->
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app.js')
            .then(null, console.error.bind(console));
    </script>

    <hello-world></hello-world>

  </body>
</html>

/*********************************************************************************/