Angular 2: What’s with the name?

The Angular 2 framework now supports semantic versioning, and it was announced that major upgrades (with breaking changes) will be released twice a year. In particular, in March of 2017 the version 4.0.0 will be released, in September – 5.0.0 and so on.

This is all good but the problem is that not only the versioning will be different, but Angular team is considering changing the name from Angular 2 to Angular. This will create lots of confusion in the Angular community.

First, a bit of history. The older version of this super popular Web framework is called AngularJS (currently at 1.6.0). Two years ago a complete redesign of this framework was announced, and the new framework got the name Angular 2. I guess, someone at Google suggested to keep the word Angular in the name to leverage the fact that more than 1.3 million of software developers were already using AngularJS, and most of these people would want to upgrade to the newer version of the same framework.

The problem is that Angular 2 is completely different framework, and suggesting the roadmap for upgrading existing AngularJS apps to Angular 2 is no different than suggesting a roadmap for upgrading an app from Ember or React to Angular 2. But the marketing plan worked out nicely, and more than 700K developers are using Angular 2 by now. No wonder – Angular 2 is a great framework.

People started creating Angular 2 communities to post articles, and ask for help. For example, the Reddit’s Angular 2 community is pretty active and has 6800 members: https://www.reddit.com/r/Angular2/. Questions and answers on StackOverflow are marked with the tag #angular2: http://stackoverflow.com/questions/tagged/angular2. LinkedIn has a group of 7900 Angular 2 developers: https://www.linkedin.com/groups/8434339.

Bloggers (myself included) are posting articles and tutorials that have Angular 2 in their names. PluralSight, Lynda.com, egghead.io and many independent developers produce video contend with Angular 2 in their titles.

Book authors (myself included) wrote about a dozen books with Angular 2 in their titles, and these books will remain relevant and useful for several years, unless Google will decide to completely re-write this framework again.

If the framework will be renamed to Angular, anyone searching for Angular 2 content will be inevitable getting materials for both AngularJS and Angular 2. Just try finding posts on StackOverflow tagged as Angular: http://stackoverflow.com/questions/tagged/angular. The “angular” in the URL will be automatically converted to “angularjs” and you’ll be seeing 200K+ irrelevant posts about AngularJS. IMO, it’s a disservice to the community. BTW, there is Angular Reddit group as well: https://www.reddit.com/r/angular, and these developers may want to keep their forum clean from Angular 2 posts.

I suggest to keep Angular 2 as the name of the framework. The digit 2 here won’t represent the version, but rather the next generation of this framework. So in March we’ll get Angular 2 v. 4.0.0, in September – Angular 2 v.5.0.0 and so on. Content producers can still include “Angular 2” in the titles and use the tag #angular2 in social networks.

What do you think?

P.S. The community may decide to keep using the tag #angular2 regardless of the official name of this framework.

A Web developer’s reading list

Manning is planning to release a free book sampler that would include chapters from different books covering modern Web development process. They asked me to select books/chapters and write a short intro, which I did and decided to share this with you.

The modern world of Web development requires software engineers who are well versed in multiple disciplines. Of course, familiarity with the JavaScript syntax is a must. As Atwood’s law states, “Any application that can be written in JavaScript, will eventually be written in JavaScript”. Well, maybe not in the pure JavaScript, but in its more productive superset called TypeScript.

Web developers use frameworks and/or libraries to avoid re-inventing the wheel while working on applications. While many people are still happy with jQuery, more progressive developers are debating: Angular or React? This comparison is wrong because React is a library while Angular is a framework with batteries included. But Angular and React are the most popular tools in the Web development ecosystem today.

There is a trend to develop applications using principles of reactive programming. The data consumer subscribes to the data stream that’s pushed to the consumer only when the data is available. This is an alternative to the polling model that requires the client to make periodic requests for data, which may or may not not be available. The RxJS library implements the push model via observable streams of data. This library offers you a variety of chainable operators (functions) that handle and transform the data en route.

Making your application available on mobile devices is important. Will your Web application look good on a small screen or you’d better create separate native applications for each mobile platform? There is is a third approach to create so called hybrid applications that run a Web container inside your mobile device translating HTML elements into their native counterparts. Actually there is a forth approach that suggests reusing the most of the code base of your Web app while compiling the UI portion into native mobile components before the app is deployed. NativeScript is one of the frameworks that does it.

Most Web applications would need to provide login and user authentication/authorization. The chances are that you’ve been offered by some apps to login using their FaceBook or Twitter account. Usually such authorization is implemented using OAuth protocol. You can set up authorization using privately installed OAuth server that fits nicely with RESTful Web services.

This book sampler will give you a taste of multiple facets of the modern development of Web and mobile applications. Some of the books are already released while others are still in the works, but you can reading drafts via Manning’s MEAP program.

For this sampler I’ve suggested selected chapters from the following books:

1. RxJS in Action MEAP

2. Angular 2 Development with TypeScript

3. React in Action MEAP

4. NativeScript in Action MEAP

5. OAuth 2 in Action MEAP

This is not a complete list and there are other fine books being released by many book publishers. Here’s my message to you

“Read.Study.Write.Repeat.”

Happy reading!

Angular 2: Implementing master-detail using router

In my blog about passing data to routes I mentioned that you can subscribe to parameters changing over time. In this blog I’ll show you how to do it by implementing master-detail functionality using the router.

Imagine, you have a list of products and, when the user clicks on one of the products, you need to show product details. There are different ways of implementing such functionality, but I’ll implement the use case when the product details functionality is implemented by a separate component that is created by the Angular router. The master part is represented by the list of mobile phones id/description, and the details about selected phone will be displayed by the component ProductDetailComponent that will be created by the router when the method Router.navigate() will be invoked for the first time. The following screen shot was take when the user selected the phone with ID=3. The bottom portion shows the details of this phone rendered by the ProductDetailComponent (on the cyan background) inside the <router-outlet>.

master-detail2

If the user will select another item from the list, its ID will be passed to the route and the respected product details will be displayed. Note that the URL will be change when the user selects different product.

Let’s start with the ProductDetailComponent. Angular router comes with the class ActivatedRoute that among other things stores the data received by the route. If you’ll read the source code of ActivatedRoute you’ll see the following properties there:

/**
* The matrix parameters scoped to this route. 
* The observable will emit a new value when
* the set of the parameters changes.
*/
params: Observable<Params>;

/**
 * The current snapshot of this route.
 */
snapshot: ActivatedRouteSnapshot;

In the previous blog I showed the example of using the snapshot property, which is exactly what the name states – a one time snapshot of the router state. The Router would create an instance of the ProductDetailComponent, where we’d inject the instance of ActivatedRoute and get the id of the phone:

  constructor(private route: ActivatedRoute) {
    this.productID = route.snapshot.params['id'];
  }

If the user would click on the link or invoke navigate() for the first time, the instance of the ProductDetailComponent would be created. But what if the instance of this component has already been created, but the user takes actions that results in multiple invocations of navigate() to the same route? The instance of ProductDetailComponent already exists, its constructor won’t be invoked again, and no new snapshots of the router states will be taken. This is where subscribing to an Observable stream comes in.

  constructor(private route: ActivatedRoute) {

    this.route.params.subscribe(
        params => this.productID = params['id']
    );
  }

The code of the constructor is still invoked once, but now it creates a subscription to the data stream that can be pushed to the route. Of course, if the user will navigate to a different route, the instance of ProductDetailComponent will be destroyed and detached from DOM, and the subscription will be over. But in our application we’ll configure just one route so the subscription will stay alive once created. Below is the entire code of the ProductDetailClass:

import {Component} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'product',
  template: `<h3 class="product">Details for product id {{productID}}</h3>`,
  styles: ['.product {background: cyan; width: 200px;} ']
})
export class ProductDetailComponent {
  productID: number;

  constructor(private route: ActivatedRoute) {

    this.route.params.subscribe(
        params => this.productID = params['id']
    );
  }
}

The code that configures the routes, renders the list of products and arranges the navigation is shown next.

import {Component} from '@angular/core';
import {Routes, Router} from '@angular/router';

const routes: Routes = [
    {path: 'product/:id', 
      component: ProductDetailComponent}
];

class Product {
    id: number;
    description: string;
}

@Component({
    selector: 'app',
    template: `
        <ul style="width: 100px;">
           <li *ngFor="let product of products"
            [class.selected]="product === selectedProduct"
            (click) = onSelect(product)>
              {{product.id}} {{product.description}} 
           </li>        
       </ul>
        
        <router-outlet></router-outlet>
    `,
    styles:[`.selected {background-color: cornflowerblue}`]
})
class AppComponent {

    selectedProduct: Product;

    products: Product[] = [
        {id: 1, description: "iPhone 7"},
        {id: 2, description: "Samsung 7"},
        {id: 3, description: "MS Lumina"}
    ];

    constructor(private _router: Router){}

    onSelect(prod: Product): void {
        this.selectedProduct = prod;
        this._router.navigate(["/product", prod.id]);
    }
}

The most interesting steps are the following:

1. We have configured one route that expects the product ID as a parameter:

const routes: Routes = [
    {path: 'product/:id', 
       component: ProductDetailComponent}
];

2. We asked Angular to inject the Router object so we can invoke its method navigate()

    constructor(private _router: Router){}

3. When the user selects a phone from the list, we invoke the click handler passing the selected product to it:

(click) = onSelect(product)>

4. When the product is selected, we want to navigate to the route configured in step 1. If this is the first time the user selects the product, the instance of ProductDetailComponent will be created, otherwise, the existing instance will receive the selected product ID.

onSelect(prod: Product): void {
    this.selectedProduct = prod; // to apply proper styles to the selected product

    this._router.navigate(["/product", prod.id]);
}

Angular uses RxJS and Observables in multiple places, and in this blog I’ve illustrated the use of observable stream with the router.

That’s all there is to it. To see this app in action, check out this plunk.

My Angular 2 presentations for 2017

In 2017 I’m planning to speak at several conferences related to development of Web applications with the new Angular 2 framework. Below is the list of my presentations (each one is 90-min long). All of them can be delivered as a 2-day workshop in your organization.

Mastering TypeScript

TypeScript is a superset of JavaScript, which allows you to be more productive in writing JavaScript applications. The syntax of this language is pretty easy to pick up for anyone who’s familiar with such object-oriented languages as Java or C#. During this presentation you’ll learn the syntax of this language and will understand the benefits it brings to the table.

Make a facelift to your Angular 2 app with UI libraries

Commercial applications need to be good looking, which means that you should pick up a rich library of UI components for your app. While Angular Material library offers two dozen of great looking components, this may not be enough for your application needs. The good news is that there are other libraries that you can use. In this presentation we’ll start with an overview of Angular Material components. Then we’ll proceed with another open-source library called PrimeNG, which offers more than 70 UI components. Finally, we’ll review the code of an Angular 2 app that uses both Angular Material and PrimeNG components.

Angular 2 for Java developers

Angular 2 is a complete re-write of the super popular Web framework AngularJS. According to Pluralsight survey, Angular leads the list of what developers want to learn in 2016. Angular 2 is a component-based framework that will have an effect in JavaScript community similar to what Spring framework did for Java. This presentation is an overview of this hot framework, which in combination with TypeScript, finally made Web development understandable for Java developers. At the end of the presentation you’ll see a sample Web application written in Angular 2 on the front and Java on the server.

Angular 2: Working with the component router

In this session you’ll see how to use the router that comes with Angular 2 Final. We’ll start with configuring the navigation in a simple app. Then you’ll see how to pass data to routes, work child routes, and create apps with multiple router outlets (auxiliary routes). We’ll also review a unit-test configuration for testing router. Finally, you’ll see how how to lazy load modules using the router.

Angular 2: Communication with the server via HTTP and WebSocket protocols

In this session you’ll see how create an Angular 2 app that can communicate with the servers via a pull (HTTP) and push (WebSocket) modes. We’ll program a simple Node server and then will go through a number of code samples that communicate with it using HTTP and WebSocket protocols. We’ll start with creating a simple NodeJS server, and then will enable it to handle HTTP requests from an Angular 2 app. Then you’ll see how to wrap a service into an observable stream. Finally, we’ll teach our server to perform a data push to an Angular 2 client using the WebSocket protocol.

Implementing inter-component communication in Angular 2

Angular 2 is a component-based framework with a well-defined API for passing data to and getting data from a component. Any application is a tree of components that often need to communicate with each other.
In this presentation you’ll see how to create reusable application components that can exchange data with each other in a loosely-coupled manner. You’ll see how components can communicate via a common parent or via an injectable service. You’ll see how to pass data using component router, input and output parameters, events and callbacks. You’ll also learn how to use projection (formerly known as transclusion) to pass HTML fragments to a component’s template. We’ll also touch upon the incorporation of the third-party JavaScript libraries into an Angular 2 app.

Using Observable Streams in Angular 2

Angular 2 includes RxJS, which is a library of reactive extensions built on the premise that everything is an observable stream.

Observables allow to introduce the push model to your application. First we’ll get familiar with the RxJS library, and then will continue reviewing observables in Angular 2. In this presentation you’ll see how to treat UI events, HTTP, and WebSocket connections as observable streams that push data. You’ll see how to wrap up any service into an observable stream so your application components can subscribe to it.

Angular 2 Tooling

Learning Angular 2 is easier than AngularJS, and developing in TypeScript is more productive than in JavaScript. But setting up the project and deploying the application is not straightforward. This presentation is not about the Angular 2 syntax. We’ll discuss the development process with Angular 2 starting from setting up the project to deploying an optimized application. We’ll start with discussing the Angular/TypeScript project structure and the proceed with such topics as using the module loader SystemJS, installing type definition files, bundling the app with Webpack and deployment in dev and prod. Finally, we’ll go through the process of scaffolding and bundling projects using the Angular CLI tool.

Angular CLI: Speed up installing dependencies with Yarn

Initially the entry barrier into the world of Angular development was pretty high because of the need to learn and manually configure multiple tools. Even to get started with a simple application, you need to know and use the TypeScript language, the TypeScript compiler, ES6 modules, SystemJS, npm, and a development web server. To work on a real-world project, you also need to learn how to test and bundle your app.

To jumpstart the development process, the Angular team created a tool called Angular CLI (see https://github.com/angular/angular-cli), which is a command-line tool that covers all the stages of the Angular application lifecycle, from scaffolding and generating an initial app to generating boilerplate for your components, modules, services, and so on. The generated code also includes pre-configured files for unit tests and bundling with Webpack.

All this is good but a project generated by Angular CLI has a lot of dependencies that have to be downloaded and installed in the node_modules directory of your project. What’s “a lot”? Let’s use the Unix tree command to see how many files and directories exist in a project freshly generated by Angular CLI. Enter the following command in the root directory of such project:

tree node_modules

You’ll see a nicely formatted tree structure of all packages installed in the node_modules directory ai a summary line at the end, which will look like this:

6233 directories, 38656 files

This is what I mean by a lot. Actually all is relative. It clearly a lot if you compare with the content of node_modules of a jQuery project:

7 directories, 13 files

On the hand, the rumor has it that React Native installs 120K files. The software becomes more complicated every year and we have to deal with it. Anyway, Angular CLI has already created the project with all packages installed. Now, let’s delete the node_module dir in the project and reinstall it with npm install. On my laptop it takes at least 90 seconds. Can this time be improved? Yes, if you’ll use Yarn – an alternative to npm client.

Yarn is a new package manager that can be used instead of npm package manager. The plan is to use npm one last time to install Yarn, and then npm is not needed. Here’s the command to install Yarn globally:

npm install yarn -g

Now let’s run Yarn from within the root dir of our project:

yarn

This command reads (an equivalent of npm install) the list dependencies from your package.json file and installs all of them either from npmjs.org or from local cache. It takes anywhere from about one minute on the first run to install those 38K files. on the consecutive runs (after deleting node_modules) it takes 30 seconds. This is three times faster than npm! Pretty impressive.

To create a new Angular CLI project called sampleProj you can run the following command:

ng new sampleProj

The above command will generate the boilerplate code of the project in the directory sampleProj with package.json and will immediately run npm install there. On my MacBook Pro it takes at least 90 seconds. Now that we are fans of yarn, we’d like to integrate it in the initial project generation. This could be done in three steps:

1. Instruct Angular CLI to not run npm install:
ng new --skip-npm sampleProj
2. cd sampleProj
3. yarn

If you use Mac or Unix-based OS, you can combine the above three steps as follows:

ng new --skip-npm sampleProj && cd $_ && yarn

The bash parameter $_ refers to the last argument of the previous command, which is sampleProj in our case. Running the above command completes in 30 seconds, which is a lot better than 90, isn’t it?

For a regular non-CLI Angular project Yarn needs about 19 seconds on the first run and 12 seconds or less thereafter. On your computer the results may be different.

Being more performant is not the only advantage of using Yarn over npm, and you can read more about Yarn’s architecture and benefits in Yarn blog. At the time of this writing Yarn is still at its early stages, but you can start using it today.

Angular 2: Component communication with events vs callbacks

So a child component needs to pass some data to its parent. I use TypeScript and in this blog I’ll show you two techniques: events vs callbacks.

Emitting events

The technique with emitting events is well documented:

1. Declare a property of type EventEmitter and instantiate it
2. Mark it with an @Output annotation
3. Be nice. I mean use generics to make it obvious to other developer what are you emitting and let TypeScript compiler warn you it you’ll try me emit the object of the wrong type.

The next line shows you an example that implements all three steps in a component called PriceQuoterComponent, which will be emitting price quotes of type IPriceQuote.

@Output() lastPrice: EventEmitter <IPriceQuote> = 
                              new EventEmitter();

The above code is very declarative and easy to read even after I quit and will go to work for another company.

To actually emit/dispatch/fire the lastPrice event, you need to create an object of type IPriceQuote and invoke the function emit:

let priceQuote: IPriceQuote = {...};
this.lastPrice.emit(priceQuote);

Nice an clean. Our component is loosely coupled and reusable, because it has no strings attached to any other components. It just shoots the lastPrice event with a payload to whoever cares to listen (or subscribe) to this event. For example, a parent component can do it like this:

<price-quoter (lastPrice)="priceQuoteHandler($event)">
</price-quoter>

The event handler function is also very easy to understand, especially because its argument explicitly declares the type of the object its getting:

priceQuoteHandler(event:IPriceQuote) {...}

Callbacks

Not sure why do you even want to go this route. Most likely, because you’ve never been in the callback hell. Get ready to lose the goodness of explicit typing and be prepared to deal with the “this and that” problem. But if you insist, I’ll show you how to do it.

This time the child (PriceQuoterComponent) will declare an @Input property, which will accept the name of the callback function to be called on the parent. Remember the Hollywood principle “Don’t call me, I’ll call you”?

@Input() whoToCall: Function;

The parent will bind the name of its function to call. Now, the child instead of emitting the event will call that function on its parent:

let priceQuote: IPriceQuote = {...};

this.whoToCall(priceQuote);

The parent won’t be listening to child’s events because there won’t be any. But now the parent needs to do two things:

1. Declare and bind the function that has to be called by the child

2. Ensure that it’ll be invoked in the object that represents the parent and not on a global object. We need to pass the “this” object to the bound function, which can be done using arrow functions in ES6 or the function bind() in ES5:

@Component({
...
    template: `
   <price-quoter [whoToCall] ="fnPriceQuoteHandler">
   </price-quoter>`
})
class AppComponent {

    fnPriceQuoteHandler: Function;

    ngOnInit(){
        this.fnPriceQuoteHandler= 
              obj => this.priceQuoteHandler(obj); // ES6

        // this.fnPriceQuoteHandler=
        //     this.priceQuoteHandler.bind(this); // ES5
    }
}    

In this video I did a quick code overview of both implementations of the above components. The sources are here. I like the version with events better, and you?