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.

Advertisements

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!

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.

 

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.

Frustrated by JavaScript?

Frustrated by JavaScript?

I decided to write this blog after reading this post of a frustrated developer (he goes by the nick pistacchio) who couldn’t create a simple single-page application (SPA) in JavaScript in several days. Typically frustration is a result of unmet expectations and this is the case here as well.

If pistacchio would decide to create a simple app using the JavaScript framework he already knew, he could achieve his goal in 2-3 days allocated for this job. The problem is that he decided to achieve two goals:

1. Learn what’s going on in the modern JavaScript ecosystem
2. Develop a simple SPA

The first task takes months of studying, but he had 2-3 days. As a result, he “got stuck in an analysis paralysis loop”. Such paralysis could have happened in any modern technology. Learning the syntax of a programming language is one thing, but mastering frameworks and the tooling is a completely different ball game. My main programming language is Java, and in the past I also was frustrated with JavaScript until I accepted three facts of life:

1. JavaScript is here to stay.
2. JavaScript is THE ONLY programming language that can run on any browsers and any old and new hardware.
3. You can run, you can hide, but you can’t escape JavaScript.

The fact that you can quickly learn how to write Hello World in JavaScript is not the reason to assume that JavaScript is a toy that should just work. You have to study it. Yes, there are way too many large and small libraries. Yes, there are several package managers. Yes, there are various automation tools. This means that you need time to get familiar with some of them and pick a reasonably small gentlemen set that works for you.

I’ve been developing Web applications with Adobe Flex framework for six years. This was the best Web framework I’ve ever seen (batteries included). So what? Flash Player is dead. Accepted it and moved on. I spent two years trying to find a JavaScript framework that would make me as productive as I was with Flex. None. Nada. Nyet.

There seems to be the light at the end of the tunnel though. Here’s what works for me now (subject to change):

Web framework and the language: Angular 2 with TypeScript
Package manager: npm
Preparing application bundles: Webpack
Unit testing: Jasmine with Karma
Deployment: npm scripts
IDE: WebStorm

If this list looks too long take a look at the skills section in the resume of any professional Java developer. If it has less than 10 Java-related tools and frameworks – it’s a resume of a junior developer.

I just came back from a large conference DevNexus where most of the attendees were Java developers. After my presentation on developing with Angular 2 and TypeScript one person stopped by and said, “I used to hate JavaScript, but now I’ll look at it again”. Please do, but take it seriously and allocate enough time for learning the JavaScript ecosystem. Manage your expectations.

P.S. If your JavaScript is a little rusty watch this video, which is an excerpt from one of the online trainings I ran for Java developers.

Oracle starts catering to JavaScript community with JET

During the last several years Oracle was working on their cloud solution, and several internal teams were creating JavaScript-based Web interfaces for the cloud. At some point Oracle decided to standardize on the set of JavaScript libraries used internally, and they also developed a set of reusable Web UI components both simple (e.g. buttons and forms) as well as complex (data grids, charts, accordion, and fancy gauges). All these components are based on jQuery UI and are responsive, so they can be used on mobile devices.

Having a nice set of UI components is great, but is not enough for building Web applications, so Oracle selected several popular JavaScript libraries to support routing, data binding, module loading et al.

All these things packaged together got a name JET (see oraclejet.org), which is a toolkit for developing front end in JavaScript.

After downloading and unzipping one file you’ll get a set of well-known libraries (e.g. RequireJS, Knockout et al.) plus the library of the UI components developed by Oracle.

Based on the demo I’ve seen, it’s pretty easy to put up an application together using these components. Selecting any component from the JET Cookbook shows you a sample code that you can copy/paste in your HTML or JavaScript code.

I’ve asked Geertjan Wielenga, one of the JET product managers, if it’s possible to replace one of the libraries included into JET with another one. He responded positively and pointed me to this blog that shows how to use JET with AngularJS.

I’d be interested to see if JET’s UI components can be used together with other WebComponents-based libraries like Google Polymer. The other thing that I’d like to see if it’s possible to replace the module loader RequireJS with SystemJS that supports loading modules of different formats (including ES6 ones).

A JET plugin for the NetBeans IDE includes a convenient debugger that can be used inside the IDE. Oracle will offer support for JET, which is important for enterprise folks.

At the time of this writing the JET Website reads “Don’t use it in production (except if you’re an Oracle Cloud customer)”, but Oracle will open source it at some point in the near future, so everyone can use it both dev and prod. If I’m not mistaken, this will be the first organically open sourced Oracle product. By “organically” I mean that it came out of Oracle’s own initiative, rather than out of the takeover of another company. Try it out.

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).