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 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?

Adding PrimeNG UI components to Angular CLI projects

Angular 2 CLI is a scaffolding tool and code generator that can be used for the real world projects. It saves you a lot of typing and spares you from worrying about config files for TypeScript compiler, testing frameworks, project bundler (it uses Webpack), and deployment.

PrimeNG is an excellent library of 70+ Angular 2 UI components. In this blog I’ll list the steps you need to perform to generate new project with Angular CLI and add PrimeNG library to this project.

If you don’t have Angular CLI installed yet, install it globally:

npm install @angular/cli -g

In the terminal window generate a new project, e.g. primeng_with_cli. Since I just want Angular CLI to generate only app compnent and module files, I’ll specify the option to generate inline template and styles and don’t bother with the test spec:


ng new primeng_with_cli --it --is --spec=false

Change to the newly created directory

 
cd primeng_with_cli

Add font awesome and PrimeNG as dependencies in package.json, e.g.


"font-awesome": "^4.6.3",

"primeng": "^1.0.0-beta.20",

Since the package.json was modified, install the above dependencies:

npm install

PrimeNG requires certain global styles so its components look pretty. Angular CLI projects have a config file angular-cli.json, where you can configure project settings, and in particular it has the property styles, which is the right place to add global style. Yes, I’m talking about the style tages that you’d add in the index.html in a regular Web app.

Angular CLI generate an empty file style.css and you need to add three more CSS file that are needed for PrimeNG:


"styles": [
    
  "styles.css",

  "../node_modules/primeng/resources/themes/omega/theme.css",

  "../node_modules/font-awesome/css/font-awesome.min.css",

  "../node_modules/primeng/resources/primeng.min.css"

] 

For sanity check run your new app by entering the following command in the terminal window:

ng serve

Open the app in the browser at 
http://localhost:4200, and Webpack dev server will happily render the single-page app with the text app works! This is a basic app that Angular CLI generated for you.

Now you need to modify the code in the generated dir app.component with the code that uses PrimeNG components. You can take the sample code from this blog. You’ll need to add required PrimeNG components to imports and declarations in the application module file app.module.ts.

The dev version of the app works, and now let’s see the prod version of this cool app. To prepare a production build run this command:

ng build --prod

Angular CLI will create bundles and will deploy all the files in the dist directory of your project. Take a peek into this directory and you’ll see the bundles that are available as .js files as well as their gzipped versions. The question is, how can we serve the existing gzipped files without having the web server do it for us? A simple solution is to install a static Node server that knows how to do it. Just add node-static package as dev dependency in package.json and install it:


"node-static": "^0.7.9" 
npm install

Finally, add the following npm script command in scripts section in package.json:



"serve:dist": "static dist -H '{\"Cache-Control\": \"no-cache, must-revalidate\"}' -z"

Start the static server and it’ll serve the optimized app on port 8080:



npm run serve:dist

NOTE: Creators of PrimeNG promised to add AoT support in the release candidate that will be available within a couple of weeks. When it’s done, you’ll be able to create smaller bundles by running this command:

ng build --prod --aot

That’s all folks!

Angular 2 training for your organization

If your team is interested in a hands-on, in-depth exploration of how to develop web applications with Angular 2, I can run a three day workshop in your organization. Participants will gain practical, skills while exploring the best practices and principles of developing Angular 2 applications and get familiar with multiple sample applications illustrating solutions for real-world challenges.

By the end of this live, hands-on course, participants will understand:

  • How to jump-start a new Angular project
  • How to arrange the client-side navigation in single-page applications
  • How to communicate with servers using HTTP and WebSocket protocols

And they’ll be able to:

  • Write code in TypeScript with the Angular 2 framework and deploy it in any modern web browser
  • Unit test the router, services, and components
  • Automate the building and deployment processes using the Webpack bundler and npm scripts

About your instructor

Yakov Fain is the coauthor of Angular 2 Development with TypeScript as well as a number of other technical books on programming. Yakov works as a software architect at the IT consultancy Farata Systems and develops software products for the insurance industry. A Java Champion, he has taught multiple classes and workshops on web and Java-related technologies, presented at international conferences, and published more than a thousand blog posts. Yakov lives in New York City.

What former clients say about Yakov’s Angular 2 workshops:

“The workshop is exactly what I have envisioned. The contents cover all of the critical and important aspects of the platform. It is also very hands-on. You made the training fun and engaging. The pace is also just right for impatient developers like us.”
– Emily Jeng, Princeton University

“I’ve attended several of your courses already. I think the plan and coverage are really comprehensive. I liked how we were going from a starter to the complete solution during the course and didn’t forget to talk about pros and cons and alternatives (several ways to build a form, SystemJS versus Webpack, etc.).”
— Dmitry N.

“Great class. Very thorough and great, detailed examples.”

— Coral S.

Prerequisites

Attendees must have basic knowledge of JavaScript and HTML. If you never worked with JavaScript before, please watch this video from one of the previous Yakov’s trainings. No knowledge of AngularJS 1.x is required.

Course outline

  • Unit 1. First steps with Angular 2
    • Introduction to Angular 2 architecture
    • Project structure and setup with npm
    • Brief introduction to TypeScript
    • Creating a “Hello World” app
    • Using the SystemJS loader
    • Templates and bindings
    • An overview of a sample Online Auction app
  • Unit 2. Client-side navigation and inter-component communications
    • Intro to client-side navigation with component router
    • Child routes, multiple router outlets, lazy loading of modules
    • How to install and use type definition files
    • Intercomponent communications
    • Implementing the mediator pattern
    • Projection of HTML fragments
  • Unit 3. Dependency injection and observable streams
    • Dependency injection
    • Providers and injectors
    • Promises (pull) versus Observables (push)
    • Observable events
    • Observable HTTP requests
    • Code review of the Online Auction
  • Unit 4. Working with Forms API and component life-cycle
    • Basic forms with ngModel
    • Template-driven forms
    • Model-driven forms
    • Form validation
    • The component life-cycle and hooks
    • How change detection works
  • Unit 5. Communicating with a server via the HTTP and WebSocket protocols
    • Creating a simple HTTP server with the Node.js and Express frameworks
    • Working with HTTP objects
    • Benefits of the WebSocket protocol over HTTP
    • Working with WebSockets
  • Unit 6. Unit testing and build automation
    • Unit testing with Jasmine
    • How to unit test Angular services, router, and components
    • Running tests with Karma
    • Getting familiar with the Webpack bundler
    • Working with Angular CLI

During this code participants performs many hands-on exercises. After each unit participants will spend half an hour working on a sample Online Auction app.

How to arrange this on-site training in your organization

This training is offered by Farata Systems, an IT consulting and training company. For training inquiries send an email at training @ faratasystems.com

Twenty one reason to use Angular 2 and TypeScript

Our company SuranceBay developed a platform for the insurance industry, and most of the UI for this system was written using Apache Flex framework (formerly Adobe Flex). Flex is an excellent framework for developing Web UI, but it requires Flash Player, which is not in favor anymore. Our quest for a good JavaScript framework started about four years ago.

After trying several pilot JavaScript projects we noticed a substantial drop in our developers’ productivity. A task that required one day in Flex would need three days in any JavaScript framework, including AngularJS. The main reasons were the lack of types in JavaScript, poor IDE support, and absence of compiler’s support.

When we learned that Google started development of the Angular 2 framework with TypeScript as a recommended language for development, we became early adopters. A year later we can confirm that the Angular 2/TypeScript duo is the most productive way of developing mid-to-large size Web applications that can run in any modern Web browser as well as on mobile platform.

These are the main reasons why I believe that Angular 2 and TypeScript are the right tools for developing Web applications:

1. The tooling support is as good as on Java or .Net platforms
2. TypeScipt code analyzer warns you about the errors as you type
3. Using TypeScript classes and interfaces makes the code more concise and easy to read and write
4. Clean separation between the code that renders UI and the code that implements application logic
5. The UI doesn’t have to be rendered in HTML, and there are already products supporting native UI rendering for iOS and Android
6. Angular 2 offers a simple mechanism for modularizing application with support of lazy loading of modules
7. The TypeScript compiler generates JavaScript that a human can read
8. The TypeScript code can be compiled into ES3, ES5, or ES6 versions of JavaScript
9. The router supports complex navigation scenarios in single-page applications
10. Dependency injection give you a clean way to implement loose coupling between components and services
11. Binding and events allows you to create reusable and loosely coupled components
12. Each component goes through a well-defined lifecycle, and hooks for intercepting important component events are available for application developers
13. Automatic (and fast) change detection mechanism spares you from the need to manually force UI updates while giving you a way to fine-tune this process
14. Angular 2 comes with the Rx.js library, which allows you to arrange a subscription-based processing of asynchronous data and eliminates the callback hell
15. Support of forms and custom validation is well designed
16. Unit and integration testing are well supported and you can integrate tests into your building process
17. The bundling and optimization of the code with Webpack (and its multiple plugins) makes the size of deployed application small
18. An ability to pre-compile the code eliminates the need to package Angular compiler (not to be confused with TypeScript compiler) with your app, which further minimizes the overhead of the framework
19. Angular Universal turns your app into HTML in an offline build step, that can be used for server-side rendering, which in turn greatly improves indexing by search engines and SEO
20. The library of the modern-looking UI components Angular Material 2 offers a number of modern looking components
21. The scaffolding and deployment tool (Angular CLI) spares developers from writing the boilerplate code and configuration scripts

From the management perspective, Angular 2 is appealing, because there are already more than a million AngularJS developers, and most of them will switch to Angular 2. Having a large pool of workers with specific skills is an important consideration for selecting a technology for new projects. Besides, there are more than 15 million Java and .Net developers combined, and many of them will find the syntax of TypeScript a lot more appealing than JavaScript, because of support of classes, interfaces, generics, annotations, class member variables, private/public variables, helpful compiler, and good support by familiar IDEs.

As you can see from this list, Angular 2 comes with batteries included. Check it out!

Wrote a book on Angular 2. Do I know it?

Over the last year I spent a substantial portion of my time writing a book “Angular 2 Development with TypeScript”. I wrote it with my colleague, Anton Moiseev. We are already working on real-world projects in Angular 2 for our software product SureLC that automates the work of insurance agents. We also taught multiple public and private Angular 2 workshops.

This morning after reading yet another post titled “How to learn Angular 2?”, I’ve asked myself, “Do I know Angular 2?”. The honest answer is “Kinda”. Let me explain.

First, let’s define what a developer needs to know to be productive in an Angular 2 project. I’ll color the items as the slopes marked in the ski resorts.

Green – easy Almost flat
Blue – moderate. Can get nasty is the snow is not groomed
Red – difficult, but manageable for non-experts. The slopes are steeper than blue
Black – really difficult. You have to be an expert to enjoy the ride.

Disclaimer. I can ski on black slopes, but I don’t enjoy the process. You won’t enjoy watching me going down the black slope, but I’ll arrive to the base.

skii_map

1. TypeScript. Yes, you can use other languages, but let’s get real. The framework is written in TypeScript, 90% of blog post and tutorials use TypeScript.

2. NPM package manager. America runs on Dunkin. The JavaScript world runs on packages. If a C-programmer writes a function to pad a string with spaces, JavaScript programmer tries to find an NPM package that does it and adds it as a dependency to his application.

3. Type definition files (*.d.ts). These files help TypeScript compiler understand the API of third-party libraries written in JavaScript. Starting from TypeScript 2.0 it’s relatively easy with the @types npm organization.

4. A module loader. Starting from EcmaScript 6 we think in modules, and it’s a good thing. Adding and maintaining multiple scrip tags for dependencies? No more. You’ll start with SystemJS and then most likely will switch to Webpack.

5. Unit testing framework. Go with Jasmine.

6. Test runner that allows to run unit tests against multiple browsers from a command line. Use Karma runner.

7. Module bundler. You need to bundle your app into a small number of files so the browser won’t make several hundreds of network requests to load Angular modules. We use Webpack.

8. Task runner. Don’t even think of starting writing the app before setting up your build automation process. Start with using npm scripts. If you’ll run into any limitations, add some Gulp scripts.

9. Angular Router. This piece has been completely rewritten three times over the last year. It’s turning into a really powerful component.

10. Dependency Injection. Works really well and is stable.

11. Forms API. It’s still changing, but is getting there.

12. Inter-component communications. It’s important to architect your applications properly so components communicate in a loosely coupled way.

13. Reactive extensions RxJS. For async communications Angular 2 uses Observables and Subscribers instead of Promises.

14. The Http module. Responsible for communication with Http servers

15. Change detection (Zone.js). This piece monitors all async changes in your components and updates the view. For most apps you don’t need to worry about it, but if you’ll need to optimize the performance of your app, plan to invest some serious efforts to learn it.

16. UI components. Angular Material 2 is in its infancy with only 15 available components. If you need to deploy your app in prod this year, go with Wijmo 5 or PrimeNG

17. Angular CLI. This tool is in its infancy as well. It allows to quickly generate the project components and create the build. It starts with downloading the entire Internet to your computer and then generates stuff. My position is wait and see.

18. IDE. I saved this item for the happy ending. The IDEs used for TypeScript and Angular 2 are almost as good as their peers in Java or C# world. We use WebStorm, but Visual Studio Code is also great.

It took me a while to get comfortable with all the items from this list. I don’t know everything, but I know where to look for a solution. The Angular documentation is sparse and lots of APIs are not documented yet. There are multiple blogs that help with solving specific tasks, but most of the blogs become outdated because Angular 2 is still changing. In particular, the introduction of @NgModule in RC.5 forces me to refactor lots of code.

In the Summer of 2015 Angular 2 was in Alpha, the API was changing weekly, but I didn’t complain:  I was an early adopter. The problem is that it’s Summer of 2016, but as of Release Candidate 5 the API is still changing and I remain an early adopter.

This list may look intimidating, but if you’ll invest enough time the results will be rewarding. I believe in 2017 Angular will become the most popular framework for developing of the front end of the medium and large web apps.

If you’re interested in learning Angular 2 in depth, enroll into one of our workshops. We’ll run the next public training   online starting from September 11, 2016. I can also deliver this workshop privately for your organization (send an email to training@faratasystems.com).

Angular 2: Guarding routes

In this blog I’ll show you how to guard routes in Angular 2 Router.

Let’s consider some scenarios that require a certain validation to be performed to decide if the user (or a program) is allowed to navigate to or leave the route:

* Allow to open the route only if the user is authenticated and authorized to do so.

* Implement a multi-part form that consists of several components, and the user is allowed to navigate to the next form section only if the data entered in the current one is valid.

* Remind the user about the unsaved changes if he or she tries to navigate from the route.

The router has the hooks that give you more control over the navigation to/from a route, and you can use these hooks to implement the any of above scenarios to guard the routes.

Angular includes a number of component lifecycle hooks that allow you to handle important events in the life of a component. First, it worth noting that the route configuration is done outside of the components. You configure routes in an object of type RouterConfig, then give it to the provideRouter() function, which in turn is given to the function bootstrap() that loads your app.
The type RouterConfig is a collection of items that conforms to the Route interface shown below:

export interface Route {
 path?: string;
 pathMatch?: 'full' | 'prefix';
 component?: Type | string;
 redirectTo?: string;
 outlet?: string;
 canActivate?: any[];
 canDeactivate?: any[];
 data?: Data;
 resolve?: ResolveData;
 children?: Route[];
}

While configuring routes you’ll typically use two properties from this interface: path and component. For example, an app that has two links Home and Product Details can specify and bootstrap the routes as follows:

bootstrap(RootComponent, [
    provideRouter([
      {path: '',        component: HomeComponent},
      {path: 'product', component: ProductDetailComponent}]),
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

But in this blog I’d like to you to get familiar with the properties canActivate and canDeactivate that allow you to hook up the routes with the guards. Basically you need to write a function(s) implementing the validating logic that will return either true or false and assign it to one of these properties. If canActivate() of the guard returns true, the user can navigate to the route. If canDeactivate() returns true, the user can navigate from the route. Since both canActivate and canDeactivate properties of Route accept an array as a value, you can assign multiple functions (the guards) if you need to check more than one condition to allow or forbid the navigation.

Let’s create a simple app with Home and Product Details links to illustrate how you can protect the product route from the users who are not logged in. To keep the example simple, we won’t use an actual login service, but will generate the login status randomly.

We’ll create a guard class that implements the interface CanActivate, which declares only one function to implement: canActivate(). This function should contain the application logic that returns true or false. If the function returns false (the user is not logged in) the application will not navigate to the route and will print the error message on the console.

import {CanActivate} from "@angular/router";
import {Injectable} from "@angular/core";

@Injectable()
export class LoginGuard implements CanActivate{

  canActivate() {
      return this.checkIfLoggedIn();
  }

  private checkIfLoggedIn(): boolean{

      // A call to the actual login service would go here
      // For now we'll just randomly return true or false

      let loggedIn:boolean = Math.random() < 0.5;

      if(!loggedIn){
          console.log("LoginGuard: The user is not logged in and can't navigate product details");
      }

      return loggedIn;
  }
}

As you see from the code, my implementation of the function canActivate() will randomly return true or false emulating the user’s logged in status.

The next step is to update the router configuration so it uses our guard. The code snippet below shows how the function provideRouter() can look like for the app that has Home and Product Detail routes and the latter is protected by our LoginGuard:

provideRouter([
  {path: '',        component: HomeComponent},
  {path: 'product', component: ProductDetailComponent,
                    canActivate:[LoginGuard]}
])

Adding one or more guards to the array given to the canActivate property will automatically invoke all guards one after the other. If any of the guards returns false, the navigation to the route will be prohibited.

But who will instantiate the class LoginGuard? Angular will do it for us using its dependency injection mechanism, but you have to mention this class in the list of providers which are needed for injection to work. We’ll just add the name LoginGuard to the list of providers in the bootstrap() function of our app:

bootstrap(RootComponent, [
    provideRouter([
      {path: '',        component: HomeComponent},
      {path: 'product', component: ProductDetailComponent,
                        canActivate:[LoginGuard]}]),
    LoginGuard,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

The complete code of the main app script is shown next:

import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component} from '@angular/core';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
import {provideRouter, ROUTER_DIRECTIVES} from '@angular/router';

import {HomeComponent} from './components/home';
import {ProductDetailComponent} from './components/product';

import {LoginGuard} from './guards/login.guard';

@Component({
    selector: 'basic-routing',
    directives: [ROUTER_DIRECTIVES],
    template: `
        <a [routerLink]="['/']">Home</a>
        <a [routerLink]="['/product']">Product Details</a>
        <router-outlet></router-outlet>
    `
})
class RootComponent {}

bootstrap(RootComponent, [
    provideRouter([
      {path: '',        component: HomeComponent},
      {path: 'product', component: ProductDetailComponent,
                        canActivate:[LoginGuard]}]),
    LoginGuard,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

If you run this app and will try to lick on the Product Details link, it’ll either navigate to this route or print the error message on the browser console depending on the randomly generated value in the LoginGuard. The snapshot below was taken after the user tried to click on the Product Details link, but the LoginGuard “decided” that the user is not logged in.

ch3_loginguard

But if our unpredictable LoginGuard “decided” that the user is logged in, the screen will look as follows after clicking on the Product Details link:

nonguarded

Dependency Injection Benefit. Since a guard is injected into your app, you can use it as any other object. For example, you can inject it in your RootComponent:

 constructor (private _loginGuard:LoginGuard){}

Then invoke any methods defined on the guard class, e.g.:

 this._loginGuard.changeLoginStatus(true);

Our LoginGuard implements the method canActivate() without providing any arguments to it. But this method can be used with the following signature:

canActivate(destination: ActivatedRouteSnapshot,
            state: RouterStateSnapshot)

The values of the ActivatedRouteSnapshot and RouterStateSnapshot will be injected by Angular automatically and may become quite handy if you want to analyze the current state of the router. For example, if you’d like to know the name of the route the user tried to navigate to, this is how to do it:

canActivate(destination: ActivatedRouteSnapshot,
            state: RouterStateSnapshot) {

      console.log(destination.component.name);
   ...
}

Implementing the CanDeactivate interface that would control the process of navigating from a route works similarly. Just create a guard class that implements the method canDeactivate(), for example:

import {CanDeactivate, Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {ProductDetailComponent} from "../product.component";

@Injectable()
export class UnsavedChangesGuard implements CanDeactivate<ProductDetailComponent>{

    constructor(private _router:Router){}

    canDeactivate(component: ProductDetailComponent){
      return window.confirm("You have unsaved changes. Still want to leave?");
    }
}

Don’t forget to add the canDeactivate property to the route configuration and inject the new guard in bootstrap(), e.g.:

bootstrap(RootComponent, [
    provideRouter([
      {path: '',        component: HomeComponent},
      {path: 'product', component: ProductDetailComponent,
          canActivate:[LoginGuard], canDeactivate:[UnsavedChangesGuard]}
    ]),
    LoginGuard, UnsavedChangesGuard,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

For a fancier way of displaying confirmation dialogs use the MdDialog component from the Material Design 2 library (see https://github.com/angular/material2). This component will be released in the upcoming Alpha 8.

NOTE: If you want to delay the navigation to a route until certain data structures have been populated, use the property resolve from the Route interface. I’ll write a separate blog showing how to do it.

In this blog I didn’t show you the code of HomeComponent and ProductDetail component, but you can find them in the Github repo with the code samples from Chapter 3 from our book Angular 2 Development with TypeScript.

If you’re interested in learning Angular 2 in depth, enroll into one of our workshops. The next one we’ll run online starting from September 11, 2016.

Angular2, npm, and TypeScript: the first steps

Angular 2 is getting more and more stable. As of July of 2016 it reached the version Release Candidate 4 and I expect to see the official release of this framework not later than in October of this year.

While developing Angular 2 applications in TypeScript is easier than in JavaScript, the initial setup of the project may be intimidating. You need to be familiar with installing and configuring NPM packages and the process of transpiling of the code from TypeScript to JavaScript.

I’d like to offer you an extract from the video from the first session of our recent online training where I show how to install the TypeScript compiler, all required npm modules, and create configuration files for npm and the module loader SystemJS. In this video I was using Angular Release Candidate 1, but you can change the versions from rc.1 to rc.4 and everything will work fine.

Our next 6-week online workshop starts on September 11. It runs on weekends and will give you a solid understanding of how to work on the real-world project with Angular 2 and TypeScript.

If you’re reading this blog after September 11, check the schedule of our upcoming trainings at yakovfain.com.

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.

Why Java Developers Will Embrace Angular 2 and TypeScript

Most of the Java developers I know don’t like JavaScript. Initially. They would give you different reasons why, but the real one is simple: too much to learn to make it work. For many Java developers creating the front end of a Web application in JavaScript is a chore to write and a burden to maintain. Nevertheless JavaScript rules in Web development and the new version of JavaScript (ES6) will make it even more popular.

ES6 offers classes, standardized module definition, arrow expressions (lambdas), predictable “this” and a lot more. Firefox and Chrome already support most of the ES6 syntax, and other browsers are getting there as well.

But there is something better than ES6: the TypeScript language, which has most of what ES6 has to offer plus types, casting, interfaces, generics, and annotations. The TypeScript code analyzer will help you to see syntax errors even before you run the program. Code refactoring works as well. In this blog I stated the main reasons of why TypeScript is the right tool for JavaScript development.

Now let’s take a quick glance at Angular 2, a complete re-write of the popular open-source framework managed by Google. There were two Beta releases of Angular 2, and it’s safe to start using it for your next Web project unless your app has to go to prod in the first half of 2016. Angular 2 is stable enough for serious development, and I know this first hand after surviving a couple of dozens of alpha releases of Angular 2.

Disclaimer. You can write Angular applications in the current JavaScript (ES5), next JavaScript (ES6), Dart, or TypeScript. Based on my experience with all these languages using TypeScript is the best option.

What makes the Angular 2/TypeScript combo so appealing to Java folks?

First of all, the code looks clean and easy to understand. Let’s do an experiment. I’ll give you a two-paragraph intro on how to write an Angular component in TypeScript followed by the sample code. See if you can understand this code.

Any Angular application is a hierarchy of components represented by annotated classes. The annotation @Component contains the property template that declares an HTML fragment to render 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 HTML from the @Component section and are implemented as the class methods.

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 lesson is over.

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:
     `<div>
          <input #prod>
          <button (click)="findProduct(prod.value)">Find Product</button>
          Product name: {{product.name}}
        </div>
    `
})
class SearchComponent {
 
   product: Product; // code of the Product class is omitted

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

A Java developer can read and understand most of this code right away. OK,ok. I’ll give you more explanations. 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 is a local template variable that stores a reference to the input field 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 field.

Note that the HTML template is surrounded with the back tick symbols, which allow you to write the markup in multiple lines in a readable form. If you prefer to store HTML in a separate file instead of template use the templateURL property:

templateUrl: './search.html' 

Dependency Injection. Angular architecture will be very familiar to those who use Spring framework or Java EE. Angular comes with the Dependency Injection (DI) module, which instantiates an object using a registered class or a factory and injects it to the application component via constructor’s arguments. The following code will instruct Angular to instantiate the class ProductService and inject it into the ProductComponent:

@Component({
   providers: [ProductService]
})
class ProductComponent {
product: Product;
 
  constructor(private productService: ProductService) {
 
     this.product = this.productService.getProduct();
  }
}

Specifying the provider and declaring the constructor with the type is all you need for injecting the object. Application components form a hierarchy, and each component may have its own injector. Injectors are not singletons.

App structure. The following image shows what the main page of a sample application is made up of. The parent component includes child components, which are surrounded with green borders.

ch2_auction_home_page_components

Router. Angular shines in development of single-page applications (SPA), where the entire Web page is never reloaded. Angular router allows you to easily configure the page fragments (the views) that should be loaded based on the user’s actions. The code snippet below includes the annotation @RouteConfig that configures two routes Home and ProductDetail, which are mapped to the corresponding components (HomeComponent and ProductDetailComponent). The user navigates the application by clicking on the links with the corresponding routerLink attribute, which will display the requested component in the area marked as <router-outlet>.

@Component({
    selector: 'basic-routing',
    template: `<a [routerLink]="['/Home']">Home</a>
              <a [routerLink]="['/ProductDetail']">Product Details</a>
              <router-outlet></router-outlet>`,
    directives: [ ROUTER_DIRECTIVES]
})

@RouteConfig([
    {path: '/',        component: HomeComponent, as: 'Home'},
    {path: '/product', component: ProductDetailComponent, as: 'ProductDetail'}
])
class RootComponent{
}

Inter-component communication. Each component in Angular is well encapsulated, and you can create it in a losely-coupled manner. To pass the data from the outside world to the component just annotate a class variable(s) with @Input() and bind some value to it from the parent component.

class OrderComponent {

    @Input() stockSymbol: string; 
    @Input() quantity: number; 
}

To pass the data from the component to the outside world, use the @Output annotation and dispatch events through this variable. Dispatch to whom? Ain’t none of the component’s business. Let’s whoever is interested listen to this event, which can be either a standard or a custom event carrying a payload.

class PriceQuoterComponent {
    @Output() lastPrice: EventEmitter<IPriceQuote>  = new EventEmitter(); 
 ...
    this.lastPrice.emit(priceQuote)
 }   

See something familiar? You got it. That thingy in the angle brackets after EventEmitter denotes a generic type, and IPriceQuote can be an interface. TypeScript supports generic and interfaces.

Casting. TypeScript supports types, classes, and interfaces (class A extends B implements D, E, F). It support type casting as well. As in Java, upcasting doesn’t require special notation. To denote downcasting surround the target type with angle brackets and place it before more general type as shown in the screenshot below.

casting

I took this screenshot after placing the cursor before value in line 17. I use WebStorm 12 IDE (a little brother of IntelliJ IDEA), which supports TypeScript quite nicely (including refactoring), and this supports improves with every minor release of WebStorm. If I wouldn’t declare the variable with the type in line 15 and wouldn’t use casting, the code would still work, but the IDE would show value in red and the code completion wouldn’t work in line 17.

Streams and lambdas. These are big in Java 8. Angular 2 incorporates RxJS, the library with react extensions, where streams is a religion. Everything is a stream in RxJS, and Angular 2 promotes using observable streams and subscribers.
Even events are streams, can you believe this? The user types in an HTML input field or is dragging the mouse, which generates a stream that you can subscribe to (think observer/observable or pub/sub).

Make an HTTP request or open a WebSocket and subscribe to the observable stream, which is a Promise on steroids. Handling results is still an asynchronous operation, but as opposed to a Promise it can be cancelled.

In Java 8 you can run a stream through a number of changed intermediate operations (e.g. map()) followed by a terminal one. In Angular 2 you can do the same:

class AppComponent {

  products: Array = [];

  constructor(private http: Http) { 

    this.http.get('/products') 
        .map(res => res.json()) 
        .subscribe(
            data => {
              if (Array.isArray(data)){
                this.products=data; 
              } else{
                this.products.push(data);
              }
            },
            err =>
              console.log("Can't get products. Error code: %s, URL: %s ",  err.status, err.url), 
            () => console.log('Product(s) are retrieved') 
        );
  }
}

If the above code requires explanations, then your Java is a little rusty. Seriously.

Module loading. One of the important features that ES6 brings to Web development is standardization of modules. The application code consists of modules (typically one module is one script file). Using the export keyword (e.g. export class Product {...}) you specify which members of the module should be exposed to other scripts. Accordingly, a script can include one or more import statements to have access to other modules.

ES6 includes the syntax for importing/exporting modules, but the standardization of the module loader System is postponed, and we use the polyfill SystemJS that can load modules of all existing formats (including ES6). When the System object will become standard in all browsers that support ES6, you won’t need to change your code (removing the polyfill is all that’s needed).

The main HTML file of he Angular/TypeScript application simply includes the configuration of the loader and transpiler (the running code must be compiled to JavaScript) and import statement of the main application component:

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

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

In the above code snippet the System object imports the module from the file app.ts, which is a root component of the application and may have child components represented by custom HTML tags. The System loader reads all import statements in each application component and loads all dependencies accordingly. Lazy loading of the modules is supported as well.

Deployment. Java developers use build tools like Maven or Gradle for deployment. Guess what, Angular developers use them as well. The TypeScript code needs to be transpiled into JavaScript, minimized and obfuscated before deployment to QA or prod servers. Some people use Grunt, some Gulp, but we use Webpack for bundling the code and npm scripts for deployment. The jury is still out on the best build automation tools, and we keep our eyes open.

I hope that after reading this blog thousands (ok, hundreds) of Java developers will want to take a closer look at Angular 2. Start with Angular architecture.

In this blog I showed you just a tip of the iceberg. You’d need to invest some time in learning Angular 2 and TypeScript, but the learning process isn’t too steep for the Java folks. If you want to make this process as pleasant as it can be, get the book that I’m co-authoring or enroll in one of our training classes.

IMHO Angular 2 will make as big of an impact in the JavaScript community as Spring Framework has in the Java world.

One more thing… View rendering is implemented in a separate tier, which means that it doesn’t have to be HTML only. You will be able to implement mobile applications that will use native iOS or Android UI components. The folks from Telerik are working with the Angular team to integrate this framework with NativeScript (read this).