Thursday, 15 December 2016

Passing data from Parent to Child Component

Passing data to a nested component

In Angular 1 we used $broadcast, $emit, $on to communicate between controllers. But now in angular 2 we have different approach.

In Angular 2, If you want to flow data from Parent Component to Child Component we use @Input Decorator or "inputs" property inside @Component decorator or in a Class. Hear we will discuss the former approach.

Our Directory Structure

Parent Component

//our root app component
import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { FormsModule }   from '@angular/forms';
import { ChildComponent } from './child.component';
import { Character } from './character';

@Component({
  selector: 'my-app',
  template: `
  <h1>@input</h1>
  <div style = "border:2px solid orange; padding:5px;">
    <h2>Parent Component</h2>
    <input [(ngModel)] = "characters[0].name"/>
    <button (click)="select(characters[0])">Input</button>
    <br/><br/> 
    <child-component [character]="selectedCharacter"></child-component>
  </div>
  `,
})
export class App {
  characters = [
    {
      "id":11,
      "name":"Name"
    }];
     
    selectedCharacter: Character;
    
    select(selectedCharacter : Character){
      this.selectedCharacter = selectedCharacter;
    }
}

@NgModule({
  imports: [ BrowserModule,FormsModule  ],
  declarations: [ App, ChildComponent ],
  bootstrap: [ App ]
})
export class AppModule {}

Child Component

import { Component, Input} from '@angular/core';
import { Character} from './character';
@Component({
  selector: 'child-component',
  template:`
  <div style="border:2px solid orange; padding:5px">
    <h2>Child Component: <span *ngIf="character">{{character.name}}</span></h2>
  </div>
  `
})
export class ChildComponent {
   @Input() character: Character;
}

Full source

Find full source from my github

Friday, 11 November 2016

platform-browser VS platform-browser-dynamic

In angular2. We must have seen in every project there is plugin called platform-browser and platform-browser-dynamic.

 "@angular/platform-browser": "2.0.0-rc.4",
 "@angular/platform-browser-dynamic": "2.0.0-rc.4",
  

Let us understand the difference.

The difference between platform-browser-dynamic and platform-browser is the way your angular app will be compiled.

@angular/platform-browser

  • It contains code shared for browser execution (DOM thread, WebWorker)
  • Ahead-of-Time pre-compiled version of application being sent to the browser. Which usually means a significantly smaller package being sent to the browser.

@angular/platform-browser-dynamic

  • It contains the client side code that processes templates (bindings, components, ...) and reflective dependency injection.
  • Uses Just-in-Time compiler and make's application compile on client-side.

When the offline template compiler is used, platform-browser-dynamic isn't necessary because all reflective access and metadata are converted to generated code.

Sunday, 30 October 2016

Object Oriented Programming in Javascript and Typescript

In this article, we will learn about basics of OOPs. In Object Oriented Programming we have 9 thing to understand like Namespace, Class, Object, Property, Method, Constructor, Inheritance, Encaplulation/Abstraction and Polymorphism.

We will cover all this 9 principle hear below with examples in Javascript and Typescript.

Namespace

Namespace is a container which lets developers bundle all functionality under a unique, application-specific name. It can help us to control the scope of class and method names in larger programming projects.

Class

Class defines the object's characteristics. A class is a template definition of an object's properties and methods.

Class is The "blueprint" from which other more specific instances of the object are drawn.

JavaScript is a prototype-based language. JavaScript uses functions as classes. Defining a class is as easy as defining a function.

   //Define the class Car
   function Car() { }
       
   class car { }
       

Object

Object is an instance of a class.

Object refers to a data structure containing data and instructions for working with the data.

Objects sometimes refer to real-world things, for example a car or map object in a racing game.

The difference between Object and class is Objects hold any information , but classes don’t have any information. Definition of properties and functions can be done at class and can be used by the object.

For creating instances of any class i.e. objects we use new keyword.

   function Car() { }

   var car1 = new Car();
   var car2 = new Car();
       
   class car { }

   let car1 = new car();
   let car2 = new car();
       

Property

Property is an object characteristic, such as color

A property is a characteristic of an object, often describing attributes associated with a data structure. It exists to kind of properties: an Instance Property which holds data specific to a given object instance, or a Static Property which holds data shared between all object instances.

   function Car(speed) {
      this.speed = speed;
   }

   var car1 = new Car(40);
   var car2 = new Car(60);

   alert("Car1 Speed: " + car1.speed);
   alert("Car2 Speed: " + car2.speed);
       
   class Car {
      speed: string;
      constructor(speed: string) {
           this.speed = speed;
       }
   }

   let car1 = new Car('40');
   let car2 = new Car('60');

   alert("Car1 Speed: " + car1.speed);
   alert("Car2 Speed: " + car2.speed);
       

Method

Method is an object capability, such as walk. It is a subroutine or function associated with a class.

It exist two kind of methods: Instance Method which are built-in tasks performed by an object instance, or Static Methods which are tasks that can be performed without the need of an object instance.

In JavaScript functions themselves are objects, so, in that context, a method is actually an object reference to a function.

To define methods in a Class, all you have to do is just define a attribute and assign an function to it.

   function Car() {
   };
   Car.prototype.speed= 'Car Speed';
   Car.prototype.setSpeed = function(speed) {
      this.speed = speed;
      alert("Car speed changed");
   };

   var car1 = new Car(40);
   var car2 = new Car(60);

   car1.setSpeed(120);
   car2.setSpeed(140);
       
   class Car {
       speed: string;
       setSpeed(speed: string) {
           this.speed = speed;
           alert("Car speed changed");
       }
   }

   let car1 = new Car();
   let car2 = new Car();

   car1.setSpeed('120');
   car2.setSpeed('140');
       

Constructor

Constructor is a method called at the moment an object is instantiated. It usually has the same name as the class containing it.

A constructor belongs to a particular class object that is instantiated. The constructor initializes this object and can provide access to its private information. Essentially, a constructor in JavaScript is usually declared at the instance of a class.

As in JavaScript there is no class keyword and the function serves as class definition, there is no need of defining constructor explicitly. The function defined for the class acts as constructor.

   function Car(speed) {
      this.speed = speed;
       alert('car is initialised');
   }

   var car1 = new Car(40);
   var car2 = new Car(50);
       
   class Car {
      speed: string;
      constructor(speed: string) {
           this.speed = speed;
           alert('car is initialised');
       }
   }

   var car1 = new Car('40');
   var car2 = new Car('60');
       

Inheritance

Inheritance is when a class can inherit characteristics and capabilities from another class.

JavaScript supports single class inheritance. To create a child class that inherit parent class, we create a Parent class object and assign it to the Child class. In following example we created a child class Ferrari from parent class Car.

   //Define the Car class
   function Car() { }
   Car.prototype.speed= 'Car Speed';
   Car.prototype.setSpeed = function(speed) {
      this.speed = speed;
      alert("Car speed changed");
   }

   //Define the Ferrari class
   function Ferrari() { }
   Ferrari.prototype = new Car();

   // correct the constructor pointer because it points to Car
   Ferrari.prototype.constructor = Ferrari;

   // replace the setSpeed method
   Ferrari.prototype.setSpeed = function(speed) {
      this.speed = speed;
      alert("Ferrari speed changed");
   }

   var car = new Ferrari();
   car.setSpeed();
       
   class Car{
      speed: String;
      setSpeed(speed: string) {
          this.speed = speed;
          alert("Car speed changed");
      }
   }

   class Ferrari extends Car{
       speed: String;
       setSpeed(speed: string) {
           this.speed = speed;
           alert("Farrari speed changed");
       }
   }

   var car = new Ferrari();
   car.setSpeed('');
       

Encapsulation

Encapsulation and abstraction is a mechanism that lets our program to hide unwanted code within a capsule and shows only essential features of an object.

Encapsulation is used to hide its members from outside class or interface, whereas abstraction is used to show only essential features.

In JavaScript, encapsulation is achieved by a a self invoking anonymous function expression.

JavaScript variables have either function scope, or global scope. There is no block scope. Enclosing our code in a self invoking function like the one in our example creates a temporary local scope for single-use, immediately-run code, without polluting the global namespace.

   (function() { 
      var x = '';
      function myFunction () {
         alert('Hello: ' + x);
      }
      x = 'Bob';
      myFunction();
      alert(typeof x);          // string
      alert(typeof myFunction); // function
   })();

   alert(typeof x);           // undefined
   alert(typeof myFunction);  // undefined
       

Whatever we declare the self invoking function is held in a separate scope. The variable x and the function myFunction() cannot be accessed from anywhere else and it would be free to declare another function myFunction() without conflicts.

In TypeScript we have option to declare Public, private, and protected modifiers like other OOP languages to do Encapsulation. In typescript all it's member are Public by default.

Typescript Private modifier

   class Animal {
       private name: string;
       constructor(theName: string) { this.name = theName; }
   }

   new Animal("Cat").name; // Error: 'name' is private;
       

Typescript Protected modifier

The protected modifier acts much like the private modifier with the exception that members declared protected can also be accessed by instances of deriving classes. For example

   class Person {
       protected name: string;
       constructor(name: string) { this.name = name; }
   }

   class Employee extends Person {
       private department: string;

       constructor(name: string, department: string) {
           super(name);
           this.department = department;
       }

       public getElevatorPitch() {
           return `Hello, my name is ${this.name} and I work in ${this.department}.`;
       }
   }

   let howard = new Employee("Howard", "Sales");
   console.log(howard.getElevatorPitch());
   console.log(howard.name); // error
         

Polymorphism

Poly means "many" and morphism means "forms". Different classes might define the same method or property.

Polymorphism is the presentation of one interface for multiple data types.

There are two approaches by which we can use Polymorphism in JavaScript. One by checking the argument types or by another approach by tracking an object at the last argument of a function.

Polymorphism by Checking Argument Type

   function CatStrings(p1, p2, p3)
    {
      var s = p1;
      if(typeof p2 !== "undefined") {s += p2;}
      if(typeof p3 !== "undefined") {s += p3;}
      return s;
    };
    
    CatStrings("one");        // result = one
    CatStrings("one",2);      // result = one2
    CatStrings("one",2,true); // result = one2true
       

Polymorphism by Tracking an object

    function foo(a, b, opts) {
    }
    
    foo(1, 2, {"method":"add"});
    foo(3, 4, {"test":"equals", "bar":"tree"});
         

However TypeScript end result is Plain JavaScript, we can only provide the single method block. Through the use of conditional statements;

   class Car{
       setSpeed(message: string);
       setSpeed(message: number);
       setSpeed(message: boolean);
       setSpeed(message: any) {
           if (typeof message === "string") {
               alert(message);
           } else if (typeof message === "number") {
               alert("The number provided was: " + message);
           } else if (typeof message === "boolean") {
               alert("The boolean value was: " + message);
           } else {
               alert(message);
           }
       }
   }

   var car = new Car();
   car.setSpeed(false);
       

Wednesday, 26 October 2016

Javascript Modules VS Angular2 Modules

Javascript Modules Angular2 Modules
Code file that import or export something Code file that organise the application
Organize our code file Organize our application
Modularize our code Modularize our application
Promote Code Reuse Promote Application Boundaries


Angular2 Architecture in Breif

The architecture diagram identifies the eight main building blocks of an Angular application:

  • Modules
    • Angular apps are modular and Angular has its own modularity system called Angular modules or NgModules.
  • Components
    • A component controls a patch of screen called a view.
  • Templates
    • You define a component’s view with its companion template. A template is a form of HTML that tells Angular how to render the component.
  • Metadata
    • Metadata tells Angular how to process a class.
  • Data binding
  • Directives
    • @Component requires a view whereas a @Directive does not. Directives add behaviour to an existing DOM element.
  • Services
    • Service is a broad category encompassing any value, function, or feature that your application needs.
  • Dependency injection
    • Dependency injection is a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services.

HTTP and Routing in Angular2 (Part 5 of 5)

Let's learn Angular 2 by an Examples and not spending much time in theory's. We will cover the best practical and ready to use Angular 2 Examples.

You can find some other posts of this series below:

Component in Angular2 (Part 1 of 5)
Directive and Pipes in Angular2 (Part 2 of 5)
Forms and Pipes in Angular2 (Part 3 of 5)
Dependency Injection in Angular2 (Part 4 of 5)
HTTP and Routing in Angular2 (Part 5 of 5)

All example are based on Angular2 RC 1

Dependency Injection in Angular2 (Part 4 of 5)

Let's learn Angular 2 by an Examples and not spending much time in theory's. We will cover the best practical and ready to use Angular 2 Examples.

You can find some other posts of this series below:

Component in Angular2 (Part 1 of 5)
Directive and Pipes in Angular2 (Part 2 of 5)
Forms and Pipes in Angular2 (Part 3 of 5)
Dependency Injection in Angular2 (Part 4 of 5)
HTTP and Routing in Angular2 (Part 5 of 5)

All example are based on Angular2 RC 1

DI - Class constructor injection

DI - Building a service

DI - Provider registration at Bootstrap and The Inject decorator

DI - The opaque token

Forms and Pipes in Angular2 (Part 3 of 5)

Let's learn Angular 2 by an Examples and not spending much time in theory's. We will cover the best practical and ready to use Angular 2 Examples.

You can find some other posts of this series below:

Component in Angular2 (Part 1 of 5)
Directive and Pipes in Angular2 (Part 2 of 5)
Forms and Pipes in Angular2 (Part 3 of 5)
Dependency Injection in Angular2 (Part 4 of 5)
HTTP and Routing in Angular2 (Part 5 of 5)

All example are based on Angular2 RC 1

Forms - Template Driven Forms

Forms - Model Driven Forms

Forms - Validation—built in

Forms - Validation—custom

Forms - Error handling

Directive and Pipes in Angular2 (Part 2 of 5)

Let's learn Angular 2 by an Examples and not spending much time in theory's. We will cover the best practical and ready to use Angular 2 Examples.

You can find some other posts of this series below:

Component in Angular2 (Part 1 of 5)
Directive and Pipes in Angular2 (Part 2 of 5)
Forms and Pipes in Angular2 (Part 3 of 5)
Dependency Injection in Angular2 (Part 4 of 5)
HTTP and Routing in Angular2 (Part 5 of 5)

All example are based on Angular2 RC 1

Directive and Pipes - Attribute directives—custom

Directive and Pipes - Using directive values

Directive and Pipes - Working with events in directives

Directive and Pipes - Angular pipes -- custom

Component in Angular2 (Part 1 of 5)

Let's learn Angular 2 by an Examples and not spending much time in theory's. We will cover the best practical and ready to use Angular 2 Examples.

You can find some other posts of this series below:

Component in Angular2 (Part 1 of 5)
Directive and Pipes in Angular2 (Part 2 of 5)
Forms and Pipes in Angular2 (Part 3 of 5)
Dependency Injection in Angular2 (Part 4 of 5)
HTTP and Routing in Angular2 (Part 5 of 5)

All example are based on Angular2 RC 1

Components - Displaying data in our templates

Components - Working with Events

Components - Using Property

Components - Using more complex data

Components - Using Sub-Component

Components - Getting data to the component with input

Components - Subscribing to component events with output

Components - Getting data to the component with @input

Components - Subscribing to component events with @output


Tuesday, 25 October 2016

Learn AngularJS 2: The Basics (Notes From Lynda.com)

All example are based on Angular2 RC 1

Displaying data in our templates

Working with Events

Using Property

Using more complex data

Using Sub-Component

Getting data to the component with input

Subscribing to component events with output

Getting data to the component with @input

Subscribing to component events with @output


Monday, 24 October 2016

Component and Event Binding

Component in Angular2

Angular 1 wasn’t built around the concept of components. Instead, we’d attach controllers to various parts of the page with our custom logic.

In Angular 2, It drops all of this for a much cleaner, more object oriented Component model.

If you are familear with OOP pattern, then you will immediately understand that component is just a class that represents an element on the screen, with member-data that influences the way it looks and behaves.

Now let's go through the Example below and we will try to understand Component and How to do Nesting Component.

Angular2 Event Binding Demo

Download Code

Get the code @ my github

Event Binding in Angular 2

Event Binding Nature

You can hook into just about any DOM-based event using the native event name like (click), (mouseup) and so on. And, you can even use this approach to bind to any DOM-based event that another directive might emit on the DOM tree.

Angular2 Event Binding Demo

Download Code

Get the code @ my github

Angular 1 VS Angular 2

Comparing Component and Controller

Angular 2

The Component

Controllers are a big part of Angular 1 that is going away in Angular 2. In Angular 2 you will probably write all your controllers as components.


  import {Component} from 'angular2/core'

  @Component({
    selector: 'my-app',
    providers: [],
    template: `
      <div>
        <h2>Hello {{name}}</h2>
      </div>
    `,
    directives: []
  })
  export class App {
    constructor() {
      this.name = 'Angular2'
    }
  }
                

    <my-app>
      loading...
    </my-app>
                

Angular 1

The Controller


var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'Hello Angular1';
});
                

  <body ng-controller="MainCtrl">
    <h2>{{name}}</h2>
  </body>
              

Structural Directives

Angular 2

*ngFor, *ngIf


    <ul>
      <li *ngFor="#ball of balls">
        {{ball.name}}
      </li>
    </ul>
    <div *ngIf="balls.length">
      <h3>You have {{balls.length}} balls</h3>
    </div>
            

Angular 1

ng-repeat, ng-if


    <ul>
      <li ng-repeat="ball in balls">
        {{ball.name}}
      </li>
    </ul>
    <div ng-if="balls.length">
      <h3>You have {{balls.length}} ball </h3>
    </div>
                

Two-Way Data Binding

Angular 2

[(ngModel)]='value'


    <input [(ngModel)]="me.name">
            

Angular 1

ng-model='value'


    <input ng-model="me.name">
                

Property Binding

Angular 2

[Property]='Property'


    <div [style.visibility]="tools ? 'visible' : 'hidden'">
      <img [src]="imagePath">
      <a [href]="link">{{tools}}</a>
    </div>
            

Angular 1

ng-property='Property'


    <div ng-style="tools ? {visibility: 'visible'}: {visibility: 'hidden'}">
        <img ng-src="{{tools}}">
        <a ng-href="{{tools}}">
          {{tools}}
        </a>
    </div>
                

Event Binding

Angular 2

(event)='action()'


    <input
      (blur)="log('blur')"
      (focus)="log('focus')"
      (keydown)="log('keydown', $event)"
      (keyup)="log('keyup', $event)"
      (keypress)="log('keypress', $event)"
      >
                

Angular 1

ng-event='action()'


        <input
          ng-blur="log('blur')"
          ng-focus="log('focus')"
          ng-keydown="log('keydown', $event)"
          ng-keyup="log('keyup', $event)"
          ng-keypress="log('keypress', $event)"
          >
            

Services and DI

Angular 2

Injectable Service

In Angular 1 we use services by using any one of Factory, Services, Providers, Constants, Values which all are covered under a provider.

But in Angular 2 all this are consolidated into one base Class.


  import {Injectable} from 'angular2/core';
  
  @Injectable()
  export class StudentService {
    getStudents = () => [
      { id: 1, name: 'Nisar' },
      { id: 2, name: 'Sonu' },
      { id: 3, name: 'Ram' }
    ];
  }
            

Using same service in Component


  import { Component } from 'angular2/core';
  import { StudentService } from './student.service';
  
  @Component({
    selector: 'my-students',
    templateUrl: 'app/student.component.html',
    providers: [StudentService]
  })
  export class StudentsComponent {
    constructor(
      private _StudentService: StudentService) { }
    students = this._StudentService.getStudents();
  }
            

Angular 1

Service


  (function () {
    angular
      .module('app')
      .service('StudentService', StudentService);

    function StudentService() {
      this.getStudents = function () {
        return [
          { id: 1, name: 'X-Wing Fighter' },
          { id: 2, name: 'Tie Fighter' },
          { id: 3, name: 'Y-Wing Fighter' }
        ];
      }
    }
  })();
            

Using same service in Controller


  (function () {
    angular
      .module('app', [])
      .controller('StdController', StudentsController);
  
    StudentsController.$inject = ['StudentService'];
    function StdController(StudentService) {
      var std = this;
      std.title = 'Services';
      std.Students = StudentService.getStudents();
    }
  })();
            

Component

In Angular 2, Components are the main way we build and specify elements and logic on the page.

In Angular 1, we achieved this through directives, controllers, and scope. In Angular 2, all those concepts are combined into Components.



To build an Angular 2 application you define a set of components, for every UI element, screen, and route. An application will always have a root component that contains all other components. In other words, every Angular 2 application will have a component tree, which may look like this:

5VhPb6M+EP00HHcFGGhybLtp9/KTVuphd48OTMCqwcg4f+inrw3jEIemza9VmkabQ5R5NmP7vWePiUduy829pHXxn8iAe6GfbTzywwvDycTX3wZoeyD2dWSAXLKsh4IBeGBPgCA+ly9ZBo3TUQnBFatdMBVVBalyMCqlWLvdFoK7o9Y0tyMOwENK+Rj9zTJV4LLCZMB/AssLO3KQTPuWOU0fcymWFY7nhWTRffrmktpcuNCNjxkSBFoEYkxY08qZ0pMQpQNIaAb6cLnMZaSiKyfmrHp0CZoLmYHcmRmZaXWlEDqR+VVuboEbha16YeKHizidJHQaTefz4Fs//btju28JllDhZD+aEh22onyJdFzXNWcpZYqJqm9sVGsl7kQCkyzwyM26YAoeapqa1rX2tMYKVXJsbgqaiTUGOaeNoU8rdYNjglSA3j9mZV0fXNY9iBKUbI0ZsPsEc+DmsdZYD04MrH+KHRfafhS1zbeZBxr1D2TySFbJiNU7xhXI5oIIDRKX0MAeT2dhNBoxOitrLlrQB97lcBr5X4nT+CCnl7Tvp7YG9DGx1fAslGKpu2xKoy9F6dWI0hGVUGXX5v6io9Rww1KXPU2EbP8Yxr7HNvyLBMKGqZ0mHZkW81Q/DGSjS89bxOq5iaXslHyl5CoqcziUpysgY4F2BIhf4N9iEjhVbOXO+yVRcIRfgukVDVvKamtPKbKna788fGr3trGf6MpNZE87m6enYJSns8h21e9zzeRfdE1XJM/lGhLt1bb90+BY15AYxTtkvxPaBt8fPmSbT7fGWWW3tWHv2v3/RT9Qcz5BdDvUaVR/7Rg5qSPeOCy6q8q5XBNt39xxdtE7fbO9QWMiW3E+bBsdDm/yfffhTxsyewY=

LET US SEE A SIMPLE COMPONENT