Featured

My speaking and training schedule

I’ll be speaking at conferences and teaching various Angular-2 classes. Here’s the list of upcoming engagements:

Angular Summit, Chicago, May 17
– Angular 2 Tooling
– Using Observable Streams in Angular 2

JEEConf, Kiev, Ukraine, May 21
– Reactive Thinking in Java
– Angular 2 for Java Developers

* Two-day workshop “Angular 2 Development with TypeScript“, Kiev, Ukraine, May 23-24

* ITEM Conference, Dnepropetrovsk, Ukraine, June 2
My Manager Sucks!

Reactive thinking in Java, Lviv JUG, Ukraine, May 25

* One day workshop “Creating Angular 2 clients for the Cloud“, Cloud Expo, New York, NY, June 7

Online workshop on Angular 2, starts on June 12

* Private two-day Angular 2 Workshop at Princeton University, June 22-23

If you’d like me to run an Angular 2 workshop for your organization please send an email at training@faratasystems.com.

Starting an Angular 2 RC.1 project

The current version of Angular is Release Candidate 1. This version changed the way how the framework is distributed – it comes as a set of scoped npm packages now. Any imports of the Angular classes will be done from @angular instead of angular2, for example:

import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component} from '@angular/core';

The content of package.json, index.html, and the configuration of the SystemJS loader has to be changed accordingly. This post is an extract of our book Angular 2 Development with Typescript, and it’ll show you how to get started with a new Angular 2 RC.1 project.

You can find the source code of the initial angular-seed project at https://github.com/Farata/angular2typescript/tree/master/chapter2/angular-seed.

To start a new project managed by npm, create a new directory (e.g. angular-seed) and open it in the command window. Then run the command npm init -y, which will create the initial version of the package.json configuration file. Normally npm init asks several questions while creating the file, but the -y flag makes it accept the default values for all options. The following example shows the log of this command running in the empty angular-seed directory.

$ npm init -y

Wrote to /Users/username/angular-seed/package.json:

{
  "name": "angular-seed",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Most of the generated configuration is needed either for publishing the project into the npm registry or while installing the package as a dependency for another project. We’ll use npm only for managing project dependencies and automating development and build processes.

Because we’re not going to publish it into the npm registry, you should remove all of the properties except name, description, and scripts. Also, add a “private”: true property because it’s not created by default. It will prevent the package from being accidentally published to the npm registry. The package.json file should look like this:

{
  "name": "angular-seed",
  "description": "An initial npm-managed project for Chapter 2",
  "private": true,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  }
}

The scripts configuration allows you to specify commands that you can run in the command window. By default, npm init creates the test command, which can be run like this: npm test. Let’s replace it with the start command that we’ll be using for launching the live-server that’s we’ll add to the generated package.json a bit later. Here’s the configuration of the scripts property:

{
  ...
  "scripts": {
    "start": "live-server"
  }
}

You can run any npm command from the scripts section using the syntax npm run mycommand, e.g. npm run start. You can also use the shorthand npm start command instead of npm run start. The shorthand syntax is available only for predefined npm scripts (see the npm documentation at https://docs.npmjs.com/misc/scripts).

Now we want npm to download Angular to this project as a dependency. We want Angular with its dependencies to be downloaded to our project directory. We also want local versions of SystemJS, live-server, and the TypeScript compiler.

npm packages often consist of bundles optimized for production use that don’t include the source code of the libraries. Let’s add the dependencies and devDependencies sections to the package.json file right after the license line:

  "dependencies": {
    "@angular/common": "2.0.0-rc.1",
    "@angular/compiler": "2.0.0-rc.1",
    "@angular/core": "2.0.0-rc.1",
    "@angular/http": "2.0.0-rc.1",
    "@angular/platform-browser": "2.0.0-rc.1",
    "@angular/platform-browser-dynamic": "2.0.0-rc.1",
    "@angular/router": "2.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.1",
    "@angular/upgrade": "2.0.0-rc.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "systemjs": "^0.19.27",
    "zone.js": "^0.6.12"
  },
  "devDependencies": {
    "live-server": "0.8.2",
    "typescript": "^1.8.10"
  }

Now run the command npm install on the command line from the directory where your package.json is located, and npm will start downloading the preceding packages and their dependencies into the node_modules folder. After this process is complete, you’ll see dozens of subdirectories in node_modules, including @angular, systemjs, live-server, and typescript.

angular-seed
├── index.html
├── package.json
└── app
└── app.ts
├──node_modules
    ├── @angular
    ├── systemjs
    ├── typescript
    ├── live-server
    └── …

In the angular-seed folder, let’s create a slightly modified version of index.html with the following content:

<!DOCTYPE html>
<html>
<head>
  <title>Angular seed project</title>
  <script src="node_modules/zone.js/dist/zone.js"></script>
  <script src="node_modules/typescript/lib/typescript.js"></script>
  <script src="node_modules/reflect-metadata/Reflect.js"></script>
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <script src="systemjs.config.js"></script>
  <script>
    System.import('app').catch(function (err) {console.error(err);});
  </script>
</head>
<body>
<app>Loading...</app>
</body>
</html>

Note that the script tags now load the required dependencies from the local directory node_modules. The same applies to the SystemJS configuration file systemjs.config.js shown below:

System.config({
    transpiler: 'typescript',
    typescriptOptions: {emitDecoratorMetadata: true},
    map: {
        'app' : 'app',
        'rxjs': 'node_modules/rxjs',
        '@angular'                    : 'node_modules/@angular'
      },
      packages: {
        'app'                              : {main: 'main.ts', defaultExtension: 'ts'},
        'rxjs'                             : {main: 'index.js'},
        '@angular/core'                    : {main: 'index.js'},
        '@angular/common'                  : {main: 'index.js'},
        '@angular/compiler'                : {main: 'index.js'},
        '@angular/router'                  : {main: 'index.js'},
        '@angular/platform-browser'        : {main: 'index.js'},
        '@angular/platform-browser-dynamic': {main: 'index.js'}
      }
});

In the section packages we mapped the name app to main.ts, so let’s create a directory called app inside angular-seed, and inside the app directory create an main.ts file, as follows.

----
import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component} from '@angular/core';

@Component({
  selector: 'app',
  template: `<h1>Hello {{ name }}!</h1>`})
class AppComponent {
  name: string;
  constructor() {
    this.name = 'Angular 2';
  }
}

bootstrap(AppComponent);

Here we import Component and bootstrap from Angular, which is already preloaded into the local directory node_modules.

Start the application by executing the npm start command from the angular-seed directory, and it’ll open your browser and show the message “Loading…” for a split second, followed by “Hello Angular 2!”

That’s all there is to it for the Hello World type application.

The Angular team substantially modified the Router API in RC.1. The old (beta) version is still available in the package named router_deprecated. At the time of this writing the new router is not documented and we have to read the sources to see how it works. In particular, instead of @RouteConfig you’ll need to use @Route. Instead of @RouteParam use RouteSegment. The syntax of RouterLink is a little different as well. We’ve migrated the first book’s app that uses new Router, and you can see the code here: https://github.com/Farata/angular2typescript/tree/master/chapter3/auction.
If you already have some apps written with the router from Angular 2 Beta, you’ll be safer remaining with this router for some time until it’ll be better documented and all its new features will be implemented.

If you’re interested in learning Angular 2 either get our book or enroll into our upcoming online training.

Angular 2: Exposing Child Component’s API

In Angular 2 a parent component can pass the data to its child via binding to the child’s input parameter marked with the annotation @Input(). I’ll blog about it later, but you can see how it can be done in my blog on implementing the Mediator design pattern.

In this blog I’ll show you another scenario when the parent component simply needs to use the API exposed by the child. You’ll see how a parent component can use the child’s API from both the template and the TypeScript code.

Let’s create a simple application where a child component has the method greet() that will be invoked by the parent. Our Child component will look like this:

@Component({
    selector: 'child',
    template: `<h3>Child</h3>`

})
class Child {
    greet(name) {
        console.log(`Hello from ${name}.`);
    }
}

To illustrate different techniques of calling the child’s API, the parent will use two instances of the same child component.

<child #child1></child>
<child #child2></child>

Here use local template variables that are used to for getting a reference to DOM object that represents an HTML component in the browser’s window. The names of local template variables must start with the hash sign.

To access the first child component from the TypeScript code, the parent component App will declare a variable of type Child annotated with `@ViewChild`. This annotation is provided by Angular for getting a reference to child components. This code will also invoke the method greet() declared in the Child component:

@ViewChild('child1')
firstChild: Child;
  // invoke the child's API
this.firstChild.greet('Child 1');

The second child will be accessed not from the code, but from the parent’s template as simple as this:

<button (click)="child2.greet('Child 2')">Invoke greet() on child 2</button>

The entire code of the application that uses both techniques is shown below.

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

@Component({
    selector: 'child',
    template: `<h3>Child</h3>`

})
class Child {
    greet(name) {
        console.log(`Hello from ${name}.`);
    }
}

@Component({
    selector: 'app',
    directives: [Child],
    template: `
    <h1>Parent</h1>
    <child #child1></child>
    <child #child2></child>

    <button (click)="child2.greet('Child 2')">Invoke greet() on child 2</button>
  `
})
class App implements AfterViewInit {
    @ViewChild('child1')
    firstChild: Child;

    ngAfterViewInit() {
        this.firstChild.greet('Child 1');
    }
}

bootstrap(App);

If you’ll run this application in the browser with Developer Panel open, it’ll immediately invoke the method greet() on the first child and will print the greeting on the console. This is an illustration of using of the child’s API from the TypeScript code. If you click on the button, the method greet() will be invoked on the second child, which is an illustration of the using child’s API from the template. The browser’s window will look as follows:

child_api

Note that in the above example I used the parent’s component lifecycle hook ngAfterViewInit() for invoking the API on the first child. The child’s greet() method doesn’t change its UI and simply prints the message on the console. But if you’d try to change the UI from greet() Angular would throw an exception that the UI is changed after ngAfterViewInit() was fired. The reason being that this hook is called in the same event loop for both parent and child components, and Angular by default runs in the development mode which does an additional change detection run to check the bindings, and it wouldn’t like the fact that UI has changed again on the same event.

There are two ways to deal with this issue:
1. either run the application in the production mode – invoke enableProdMode() before the bootstrap() – so Angular won’t do the additional bindings check
2. Use setTimeout() for the code updating UI to run it in the next event loop.

If you’re interesting in learning Angular 2, consider enrolling into one of our training classes. The current schedule is published here.

My two cents on the npm scandal

If you haven’t heard the story, here’s the gist of it. A guy named Azer Koçulu published 250(!) open source packages in the popular repository npmjs.org, which is a central repo for all JavaScript developers (it’s like Maven Central for Java developers).  One of the packages was named kik. Unfortunately for Azer (and all of us), there is a company with the same name, and they decided to publish the package with the same name on NPM. Due to the name conflicts, they contacted Azer asking him to rename his package that was already used by many users. Here’s the Kik corporation’s  version of the story. And this is what Azer wrote.

This is really sad. I’m with Azer 100%. There is a corporate world and there is an open source world. The corporate world loves using free and open source libraries and frameworks that help them making money. But they won’t think twice and will invest hundreds of thousands of dollars to win the case against Azer if need be.

Why a company with 270 million users rejected Azer’s offer to buy the name from him for mere $30K? Because they are a bunch of dicks as Azer correctly put it. They want free stuff.

There should be some international law that will make the commercial and the open source worlds live in parallel dimensions. If one corp uses a trademarked term from another corp, it can be sued. But they should not reach out to the open source world imposing their rules there.

We are using the JavaScript framework Jasmine for unit testing. I have a suspicion that there are some other uses of the word Jasmine.  Beside being a plant, a trading companya nail salon in Brooklyn,NY, a Thailand telecom company there are thousands establishments that use this word in their names. Now any of them can write a package that prints Hello World (even a plant can do it), and write a letter to NPM to remove the jasmine package from there.

Guys, this may open a can of worms. kik.com should back off!

Part 2 or is my application at risk

You might by thinking, “I don’t really care cause I’m not using any of Azer’s packages. I’m using Angular developed by a large company that employs hundreds of lawyers”. Wrong. In modern JavaScript ecosystem it’s very difficult to use just one thing. I’ll give you an example using one our simple projects that uses five npm packages: Angular 2, TypeScript, Jasmine, Karma, and live-server. I’ll give you a little quiz. How many packages will be installed on your computer to get these five things? Just take a look at the end of log file of the “npm install” command that I ran on my computer to install these five things.

log

That’s right. Those five packages had dependencies and 263 npm packages where installed on my computer in less than a minute. Some of them were developed by big companies, but most of them were developed by one person like Azer.

To be more specific, my application heavily depends on module loader called SystemJS (see the package #259), which was developed by the guy named Guy Bedford, a respected developer who contributed tons of code to the open source community (btw, Guy is also the author of JSPM package manager). What if for whatever reason Guy will become as angry as Azer and will remove SystemJS from npm? This will affect thousands of projects. These projects won’t stop working, because SystemJS is already installed locally, but lots and lots of people will need to spend time and find a replacement or start fixing builds, bugs and adding features to the local version of SystemJS instead of working on their applications.

Some open source developer nicely illustrated a scenario when an 11-line library responsible for left-padding strings was removed from npmjs.org. Check this out:) David Haney raises the right question, “Have we forgotten how to program?

Part 3 OMG, what do I do?

Nothing. Just accept the reality of today’s open source world. At least I live with an assumption that any of the above 263 packages may stop being developed any moment, and the versions I have already installed are the last ones. At least I have the source code…

Update. NPM has addressed this issue, and Azer won’t be able to unpublish his packages unless they are younger than 24 hours.

 

Implementing the Mediator Design Pattern in Angular 2

In any component-based framework you’ll need to implement component communications. The main principle is that components should be loosely coupled hence reusable hence testable. The mediator design pattern allows you to arrange component communications via “the man in the middle” so a component A never communicates with the component B directly. If a component needs data, someone will provide the data via bindings to the component’s input properties. Who’s this someone?Ain’t no business of the component. If a component needs to provide some data to the external world, it’ll emit events (with the data payload). Emits to whom? Ain’t no business of the component. Let whoever needs the data listen to the events from this component.

The mediator pattern is one of the ways to arrange a loosely coupled communication between components. In the following video I show an example of one of the ways of implementing Mediator in Angular 2. Here the sibling components communicate via their parent, but this could be also arranged via injecting a service into both component that need to “talk” to each other.

This video is an extract from the online training session I ran recently. If you’re interested of learning Angular 2 in a live session, here’s  my speaking/training schedule. If you can’t attend live events, get consider reading our book:  https://manning.com/books/angular-2-development-with-typescript.

What’s Happening in the JavaScript Ecosystem

Lots of things are happening there. As of today it’s the liveliest software ecosystem. The last time I’ve seen such an interesting gathering was 15 years ago in Java.

The Past

Fifteen years ago Java developers were looking down on the JavaScript folks. It was assumed that JavaScript was only good for highlighting menus and making an impression that the Web site is current by displaying a running clock on the page. Mobile phones still had buttons with one digits and three letters. There were no App stores. Java was promising “Write once run everywhere”, but now we can see that JavaScript actually delivered on this promise.

Say, you are developing in the XYZ language and wrote tons of programs in this language over the last 15 years. During this time new versions of the XYZ were released. The hardware advanced and new versions of operational systems came about. And you decided to take your old XYZ program written in the last century and run it on the brand new iPhone 6 or Android. Voila! It works without changing a line of code! I don’t know about the XYZ language, but programs written in JavaScript 15 years ago still work on iPhones.

js

Having said that, writing in JavaScript was never a pleasant experience. Some people made fun of JavaScript. Making fun of Brendan Eich, who created JavaScript in 10 days, was popular.

Other people started creating multiple libraries and frameworks to lower the pain of writing in plain JavaScript and making it work in different browsers. Ten years ago there were a couple of hundred JavaScript libraries and frameworks. People were overwhelmed by the freedom of choice well explained by Barry Schwartz in this video. The ECMAScript was abandoned. HTML5 was not born yet. In short, Web development was not fun.

The Present

In 2016 the situation is drastically different:

— The ECMAScript (ES) standard is actively being worked on, and its new versions will be released annually. Last year the ES6 (aka ES2015) spec was released and ES7 will be released this year. Now the JavaScript language has classes, lambda expressions (a.k.a. arrow functions), predictable “this”, block scope, generator functions, promises, destructuring, spread and rest operators and more. Some hardcore JavaScript developers immediately started WTF-ing classes as being a lot worse than functions, but these discussions are as useful as arguments about where to put curly braces in the if-statements: on the same or on the new line. Classes are just a syntax sugar that doesn’t change the prototypal inheritance, but reading and writing code is much easier now.

— All major browsers support most of the ES6 syntax.

— Transpilers easily generate ES5 program from the ES6 code so you can deploy the ES6 code today in all browsers.

— Dozens of languages emerged allowing you to write code that gets converted int to JavaScript automatically. The best of the breed is TypeScript created by Anders Hejlsberg from Microsoft. In the past he also created C#, Delphi and Turbo Pascal.

— Tons of open-source JavaScript code are published in various repositories. The most popular repo is npmjs.org, which has more than 200K libraries, frameworks and useful utilities. By the way, npm literally killed bower, his former competitor.

— Google created a super-fast JavaScript engine V8. The Node.js framework allows you to write standalone applications that don’t require browsers. Node servers started to compete with the ones written in Java. Despite the single-threaded architecture of I/O, Node’s asynchronous processing allows handling tens of thousands client requests simultaneously.

— There are build automation tools (we use Webpack), which minimize and optimize the JavaScript code with the further bundling separate files together so browsers don’t need to make dozens of requests to the server to download that home page.

— The WebComponents standard prescribes how to develop custom HTML components. The Material Design principles explain how to develop nice-looking Web pages. Google implemented these principles in a library of custom components called Polymer. We already tried it in the real-world projects, and it works!

– HTTP/2, a major revision of HTTP will substantially speed up the client-server communications.

Libraries and Frameworks

The number of JavaScript libraries and frameworks is comparable to the number of presidential candidates in the Republican Party in the USA. Those (mainly enterprise) folks who want to get everything out of the box and are not afraid to sell themselves into slavery still use Ext JS. This is not an easy to master framework, but it has everything you need to develop back-office enterprise applications.

Developers who want a lighter framework that puts a structure on your app with navigation and data binding usually go with AngularJS 1.x or Ember. They would need to integrate third-party libraries for graphical components, grids, and a usual Twitter’s Bootstrap (to make the app usable on mobile phones and tablets), but it’s doable. Some people prefer the React framework from Facebook, but React is mainly about views, and you’d need to use some third-party libraries to build an app.

Those who don’t like prix fixe meals and prefer a la carte menus pick a bunch of small libraries each of which can do one thing well. They are ready to face the issues while trying to make these libraries work together. Such people charge higher rates and project managers keep their fingers crossed hoping that these developers won’t quit.

Fashion Trends

In this season every top model-developer entering a catwalk wears reactive accessories. Not that “reactive” is something completely new (even our grandmas liked messaging, pub-sub, and the observer-observable pattern), but in today’s asynchronous UI world, reactive is a must have. We need to give a credit to Microsoft (do people still hate it by default?) for beautifully designed reactive extensions, which in JavaScript world go by the name RxJS.

In the reactive world every component or service is implemented as a stream. Everything is a stream. You are a stream. I am a stream. A click on a button spits out the event as a next element of a stream. An HTTP request to a server returns a response as an element of a stream (promises had their 15-min of fame and are considered old fashioned these days). A piece of data pushed over a WebSocket connection is an element of a stream you can subscribe to. And there is a nice little twist to it: a subscriber can regulate the stream volume and lower the pressure if need be.

A year ago a team from Google decided to re-write their super-popular (1.1M devs) framework AngularJS. They started with creating a new language AtScript just for the new Anguar 2, but then invited the TypeScript team from Microsoft (can we start liking Microsoft, just a little bit?), and asked them to add some features to the TypeScript language. Microsoft folks kindly agreed, and Google wrote Angular 2 in TypeScript, which also became a recommended language for developing Angular 2 apps. Now the code of Angular 2 apps is easy to read and write even for Java and C# developers (see this). Needless to say that RxJS is embedded inside Angular 2.

Jokes aside, I really like the Angular 2/TypeScript/RxJS/npm/Webpack combo. During the last ten months I’ve been working with my colleague Anton Moiseev on the book “Angular 2 Development with TypeScript“. So far Manning published 300 pages of this book, and the remaining 150 pages are almost ready. The code faindz will lower the price of the eBook by 39%.

If you prefer to learn Angular 2 in a classroom setting, this year I’ll be teaching Angular 2 classes and my training/speaking schedule is published here.

The Bottom Line

My hat off to Brendan Eich for not over-engineering the language. JavaScript is getting a lot of traction and the demand for professional JavaScript developers will grow by leaps and bounds. Be there and stay current.

Angular 2: High-Level Overview

This article was excerpted from the book “Angular Development With TypeScript” (see http://bit.ly/1QYeqL0). You may also look at my other high-level overview of Angular 2 published by InfoQ.

The Angular 2 framework is a re-write of popular framework AngularJS. In short, the newer version has the following advantages over AngularJS.

  • The code is simpler to write and read
  • It performs better  than AngularJS
  • It’s easier to learn
  • The application architecture is simplified as it’s component-based

This article contains a high-level overview of Angular highlighting improvements comparing to AngularJS. For a more detailed architecture overview of Angular visit product documentation at http://bit.ly/1TQJmwG.

Code Simplification

First of all, an Angular application consists of standard ES6 modules. Typically one module is one file. There is no need to use a framework-specific syntax for loading and using modules. Just use the universal module loader SystemJS (covered in Chapter 2) and add import statements to use functionality implemented in the loaded modules. You don’t need to worry about the proper order of the <script> tags in your HTML files. If a module A needs the functionality from a module B, just import the module B inside module A.

The HTML file of the landing page of your application just includes the framework modules, and your application code is bootstrapped by simple loading of the root component of your application. All child modules will be loaded automatically based on the import statements. Below is a typical content of the index.html of an Angular application. In the top portion you include the required framework modules, and at the bottom you configure the system loader and load the root component located in the file app/my_application.ts. The <app> tag is a selector defined in that root component.

<!DOCTYPE html>
<html>
<head>
  <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
  <script src="node_modules/typescript/lib/typescript.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>

</head>
<body>
  <app>Loading...</app>

  <script>
    System.config({
      transpiler: 'typescript',
      typescriptOptions: {emitDecoratorMetadata: true},
      packages: {app: {defaultExtension: 'ts'}}
    });
    System.import('app/my_application');
  </script>
</body>
</html>

The HTML fragment of each application component is either inlined inside of the component (the template property) or in the file referenced from the component using the property templateURL. The latter option allows designers to work on the UI of your application without the need to learn Angular.

An Angular component is a centerpiece of the new architecture. The next Figure shows a high-level diagram of a sample Angular application.

ch1_angular2_workflow

The simplest way of declaring a component is writing a class in TypeScript (you can use ES5, ES6, or Dart as well). Let’s do an experiment. We’ll give you a super brief intro on how to write Angular components in TypeScript followed by the sample code. See if you can understand the code with minimum explanations.

An annotated TypeScript class represents a component. The annotation @Component contains the property template that declares an HTML fragment to be rendered by the browser. The HTML piece may include the data binding expressions, which can be represented by double curly braces. If a view depends on other components, the @Component annotation has to list them in the property directives. The references to the event handlers are placed in the markup from the @Component section and are implemented as methods of the class.

The annotation @Component also contains a selector declaring the name of the custom tag to be used in HTML document. When Angular sees an HTML element with the name matching a selector, it knows which component implements it. The HTML fragment below illustrates a parent component with one child component :

<body>
  <auction-application>
    <search-product [productID]= "123"></search-product>
  </auction-application>
</body>

A parent component sends the data to its child components using property binding (note the square brackets above), and children communicate with their parents by sending events. The next Figure shows the main page (the parent component) with its child components surrounded with thick borders.

ch2_auction_home_page_components

Below is a code sample of a SearchComponent, and we can include it in an HTML document as <search-product> because its declaration includes the selector property with the same name.

@Component({
  selector: 'search-product',
  template:
     `
<form>
<div>
          <input id="prodToFind" #prod>
          <button (click)="findProduct(prod.value)">Find Product</button>
          Product name: {{product.name}}</div>
</form>

    `
})
class SearchComponent {
   @Input() productID: number;

   product: Product; // code of the Product class is omitted

   findProduct(prodName: string){
	// Implementation of the click handler goes here
   }
   // Other code can go here
}

If you are familiar with any object-oriented language that has classes you should understand most of the above code. The annotated class SearchComponent declares a variable product, which may represent an object with multiple properties, one of which (name) is bound to the view ({{product.name}}). The #prod will have a reference to the hosting <input type=”text” /> element so you don’t need to query DOM to get the entered value.

The (click) notation represents a click event, and the event handler function gets the argument value from the input parameter productID that will be populated by the parent component via binding.

This was just a quick look at the sample component, but we’ll be providing a detailed description of what components are made up of starting from the next chapter.

If you never worked with classes before, no worries. We’ll cover them in Appendices A and B. The next Figure illustrates the inner working of a component.

ch1_angular_component

A component uses the data from a model (the M in the MVC pattern), which can be also represented by a class. In TypeScript the model class for a SearchComponent could look like this:

class Product{
    id: number,
	name: string;
	description: string;
	bid: number;
	price: number;

	// constructor and other methods go here
}

Note that TypeScript allows you to declare class variables with types. To let the UI component SearchComponent know about its model you can refer to it by declaring a class variable, e.g. product:

@Component { // code omitted for brevity}
class SearchComponent {
   product: Product;  // the model

   findProduct(productID){
	   // The implementation of the click handler
	   // for the Find Components button goes here
   }
}

If the search component may return multiple products we can declare an array to store them:

products: Array<Product>;

The generics notation (explained in Appendix B) tells the TypeScript compiler that only the objects of the type Product are allowed to be stored in this array.

In Angular there are no separate controllers (the C in the MVC pattern). The component includes all required code. In our example, the SearchProduct class would contain the code performing the controller’s responsibilities in addition to being a UI component on the HTML view. For a cleaner separation of TypeScript and HTML, the content of the template section of the @Component annotation can be stored in a separate file by using templateURL instead of template, but it’s a matter of your preference.

Developers who know AngularJS can think of a component as a directive with a view, but writing directives without views is still allowed.

Now let’s see how the design of Angular is simpler than of AngularJS. In AngularJS all directives were loaded to the global memory, whereas in Angular you specify the required directives on the component level providing better encapsulation.

You don’t have to deal with the hierarchy of scope objects as in AngularJS. Angular is component based, and the properties are created on the this object, which becomes the component’s scope.

Dependency Injection is a design pattern that inverts the way of creating objects your code depends on. Instead of explicitly creating object instances (e.g. with new) the framework will create and inject them into your code. Angular comes with a dependency injection module. We’ll cover dependency injection in Chapter 4.

In AngularJS there were several ways of injecting dependencies, which could be confusing at times. In Angular you can inject dependencies into the component only via its constructor. The following TypeScript code fragment shows how to inject the ProductService component into the SearchComponent. You just need to specify a provider and declare the constructor argument with the type that matches provider’s type.

@Component({
  selector: 'search-product',
  viewProvider: [ProductService],
  template:[
<div>
...
<div>]
})
class SearchComponent {
  products: Array<Product> = [];

  constructor(productService: ProductService) {
    this.products = this.productService.getProducts();
  }
}

To summarize, Angular is simpler than AngularJS because of the following:

  • Each building block of your app is a component with well encapsulated functionality of a view, controller, and auto-generated change detector.
  • Components can be programmed as annotated classes.
  • A developer doesn’t have to deal with scope hierarchies.
  • Dependent components are injected via the component’s constructor.
  • Two-way binding is turned off by default.
  • Change detection mechanism was re-written and works faster.

The concepts of Angular are easy to understand for Java, C#, and C++ programmers, which represent the majority of enterprise software developers. Like it or not, but a framework becomes popular when it gets adopted by enterprises. Today AngularJS is widely adopted by the enterprises, and AngularJS skills are in big demand. Since developing applications with Angular is easier than with AngularJS this trend should continue.

Performance Improvements

 

To compare performance of AngularJS and Angular 2 the creators of these frameworks developed a benchmarking tool called Benchpress (see http://bit.ly/1IvgnKZ), which showed some serious performance improvements in the area of rendering and memory use.

The rendering improvements are mainly the result of the internal redesign of the Angular framework. The UI rendering and the application API were separated into two layers, which allows to run the non-UI related code in a separate Web Worker thread. Beside the ability to run the code of these layers concurrently, Web browsers allocate different CPU cores to these threads when available. You can find a detailed description of the new rendering architecture in the document titled Angular 2 Rendering Architecture available at http://bit.ly/1CEXjIl.

Creating a separate layer for rendering has an additional important benefit: an ability to use different renderers for different devices. Every component includes the @Component annotation that contains an HTML template defining the look of the component. If you want to create a component to display stock prices in the Web browser its UI portion may look as follows:

@Component({
  selector: 'stock-price',
  renderer: 'DOMRenderer',
  template: '
<div>The price of an IBM share is $165.50</div>
'
})
class StockPriceComponent {
...
}

Currently, DOMRenderer is the only renderer, so you don’t even need to include it in the @Component annotation. But the Angular team already works on creating native renderers for mobile devices running iOS and Android. Such renderers should be released in the near future, and Angular applications won’t need to run inside the Web View (embedded Web browser) on mobile devices – they’ll use native UI components.

A new and improved change detection mechanism is yet another contributor to better performance. Angular doesn’t use two-way binding unless you manually program it. One-way binding simplifies the detection of the changes in an application that may have lots of interdependent bindings. Now if a component has only internal immutable objects, you can mark it as such so it won’t be checked when a change is detected in another component.

Although Angular 2 is a complete re-design of Angular 1, those of you who use AngularJS can start writing code in Angular 2 style by using ng-forward (see http://bit.ly/1PNXFmH). The other approach is to start gradually switching to a newer version of this framework by running Angular 2 and Angular 1 in the same application (see http://bit.ly/1YixNzE), but this would increase the size of the application.

“To learn more about Angular see the book “Angular Development with TypeScript” at http://bit.ly/1QYeqL0 and save 39% with discount code faindz.  For the up to date information about our Angular 2 training visit this page.