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

49 thoughts on “Why Java Developers Will Embrace Angular 2 and TypeScript

  1. Two years ago we held off on moving off of Flex and moving to HTML5 because I felt it just wasn’t a good fit for us compared to Flex. After reading your blogs on Angular, I feel it’s time to look at HTML5 again.

    Another framework that has been compared to Angular is Aurelia. Yakov, any thought you would like to share about Aurelia?

    1. Jim, we also held off on moving from Flex to any HTML5 framework. To put it simply, there was nothing as good as Flex in the JavaScript world.

      From the productivity point of view there is still no JavaScript framework that can compare with Flex. But now at least we see a light at the end of the tunnel. We did a pilot project combining two Google’s products: Angular 2 (for the app) and Polymer (for the UI components) using TypeScript as a language. It seems to work better than any other JavaScript-based set of frameworks we tried.

      Later this year we’re planning to replace Polymer with Angular Material 2 when it’s ready. In February we’ll start our internal company training to get a group of Flex developers to learn the new set of tools. Initially they will be screaming, but we gotta do it.

      I never worked with Aurelia.

      1. Curious about how you combined angular with polymer. This seems like overlap and I’m trying to understand where polymer fits in or if at all in future web development.

        1. Polymer gives you a bunch of nice-looking responsive UI components off the shelf, and you can create your own as well. Angular 2 doesn’t offer UI components at the moment (until Material Design 2 is released), but it offers a nice way to build single-page apps. So there is no overlap.

          Initially we decided to build an app using just the Polymer. But then we started to add a bunch of other libraries (e.g. supporting routing et al.) to turn our components into the app. Then we decided to not reinvent the bicycle and integrated our Polymer-based components into the Angular 2 app.

  2. Well it s obvious that your company embraced Angular and TypeScript and you have to promote that. But for a java developer wanting to do front end development there better options out there than going the typescript/Angular way.

        1. Eclipse Scout and Eclipse RAP are also two UI frameworks that work in the browser.

  3. Yakov, great article. Really easy to read and embrace as for me!

    One question I have is: what’s your opinion of React JS? How do you consider its ups and downs in comparison with Angular 2?

    1. Angular is a framework while React is a library, which means that with React you’ll need to look for other libraries to construct the app. Besides, I don’t like how React mixes up JavaScript and HTML.

      For a detailed comparison search for Angular 2 vs React.

  4. Yakov,

    What would you recommend as a roadmap to learning this technology for Java developers that have very little HTML and JavaScript experience? Also, would we skip learning JavaScript and instead learn TypeScript or is JavaScript a prerequisite? Do you still recommend learning Dart before learning Angular 2?

    1. Jim, back in 2009 you started with buying our book on Flex. Was it a good roadmap? 🙂

      Manning already released 230 pages of our Angular2/TypeScript book, which you can get today. It’s a good start. If you prefer the instructor-led training, consider joining our online training class in Feb.

      You don’t need to learn Dart to get started with Angular. Dart is a good language, and it’s a pity that Google didn’t want to invest enough money to make it popular in the enterprise IT.

      1. It was a good roadmap and I was planning on getting your book but I wasn’t sure how deep of knowledge you meant for JavaScript and HTML when your class prerequisite says “working knowledge of JavaScript and HTML”.

  5. Hi, Yakov. I am currently going through a similar epiphany, except that instead of J2EE background I come from that of Rails. So my natural ally appears to be Ember.JS. I recognize the popularity of Angular, and with recent releases it becomes significantly more formidable player. Have you had experience with Ember and how do you feel it compares to Angular?

    1. Didn’t have a chance to work with Ember. In the JavaScript world one can go crazy from the variety of available libraries and frameworks. IMO, the synergy between Angular 2 and TypeScript will make this duo a winner.

  6. I have been playing with Angular 2. While a lot of what is said is true here, I am frankly pretty disappointed. Their Test docs don’t even mention Karma! They walk you through just using Jasmine in a browser (file under: over my dead body), and the errors it produces when things don’t go right make you want to go back to punch cards. After all this time? I am so sick of Google releases being basically lazy alphas that require a lot of time wasting.

  7. I think you’re correct that Java developers will be interested in Typescript/Angular 2. However, I think it’s for the wrong reasons. Enterprise Java is infamous for having bloated API’s where interfaces are often use even when they aren’t needed and adding complexity that isn’t needed. Most of the enterprise backend developers that I’ve worked with that have started using Angular 1.x are really just learning Angular and not Javascript and have no idea how Angular works and no idea how Javascript works behind the covers.

    I would strongly prefer that Angular 2 was using Javascript instead of preferring Typescript and as we know all examples will be in Typescript so it’s a moot point that you don’t need to use Typescript. I don’t think people would feel the need for a stronger typing system If people were test driving their code or least writing good, isolated unit tests.

  8. As a long time Java dev – what we like in addition to what TypeScript provides is tooling. Since Java is the number 1 Java IDE, until there is support for TypeScript and AJS 2, adoption will be low. I am sticking with AJS 1 for now. Yes, AS2 is better but i dont have to depend on JS compile tools and etc. I can use webjars to manage the JS dependencies and not worry about and extra compile step.

  9. Where to begin…

    “the real one is simple: too much to learn to make it work.”

    Seriously? Javascript is about the dumbest, simplest language I’ve ever used, besides BASIC. No, this is not the reason. JS is simple… too simple.

    http://quoteinvestigator.com/2011/05/13/einstein-simple/

    I’m sure the ugly duckling that is TypeScript will someday grow into a beautiful, well-supported language that is every bit as powerful as Java. And just as complicated (if not more so). Which rather begs the question… why didn’t we just use Java, a perfectly good, mature language for which any number of tools, IDEs, frameworks, libraries, and a vibrant community and ecosystem already exist? That’s what Google had done with GWT, until they lost their way and, apparently, started pandering to script kiddies. Having finally come to the same place that the previous generation of software developers had reached three decades ago, the Javascript community seems to have noticed that JS, while fun for hacking up websites, is not a serious language for developing software (I mean… apps) of any appreciable size. “Behold TypeScript!” they now tell us, “the statically typed, compiled language!” OK… I hope you can appreciate why are we ancient Java developers, your elders, are not fully impressed.

    Instead of re-inventing the wheel, it might have been smart simply to use the existing GWT Java-to-JS “transpiler”, which was open-sourced years ago. And then, ya know… Vaadin, anyone?

    Modern browsers now understand ES6, and that’s great. But, while we’re at it, it would have been even smarter to make web browsers that understand a real language (i.e., Java) natively. Yeah, I’m still mourning the demise of the applet.

    What about debugging? Oddly, the indispensable debugging tools (e.g., the Eclipse debugger) that have existed for Java development for nearly two decades seem to be a little-discussed consideration in all this. TypeScript compiles to JS, so a link must be provided to the native code. This implies generating a “.js.map” file, or adding funny comments at the top of each .ts file. All of this must be maintained. Using GWT in Eclipse, it just works. I never even had to think about it.

    Oh, and we are hard-coding HTML templates in the TypeScript code, are we? That’s… charming. I know, it is possible to have sane templates in HTML files, but why even allow (let alone discuss) this sort of abomination?

    1. Went through the doc of angular2boot. This is a really nice experiment! The only thing I don’t understand is why would I program Angular 2 in Java instead of TypeScript? Just because some people simply don’t want to program in anything but Java?
      What about the tooling support that exists for TypeScript? Also, why using a replica when you can use the original?

      1. Yes some people prefer Java, especially when writing quite big applications which need to be maintained for a long time.
        Apart from that, you can reuse GWT widgets with this project. You can also make your java angular components interoperate seemlessly with javascript, so that can be a win-win situation.
        The other advantage i think is for companies which use Java and want to stay focused. In this way they can easily share business code accross the front and back end …
        This also has a social impact, i saw sometimes that using the same language on front and back kept the front and back end teams close together…

        Well to resume, it’s just another option that you can choose, or not !

        Thanks

        1. Hi Arnaud,
          The Angular2Boot tutorial is so cool! I’ve just got to the point where I see the application running at http://localhost:8080/ Now I’d like to insert, just after the title, a GWT widget created with UIBinder (an ui.xml file) and using an EventBus to handle the events. This is possible, isn’t it?
          I’ve started with GWT only a couple of months ago and I’m wondering if there’s a future for it.
          Greetings from Bucharest,
          Cristina

        2. Hi Cristina,

          You can have a look at the documentation here http://lteconsulting.fr/angular2boot/gwt-widgets-integration/#widgets-inside-an-angular2boot-application It tells about inserting GWT widgets (ui binder or not) into an angular 2 component. Thanks

          Le mer. 29 mars 2017 à 15:11, Yakov Fain’s Blog a écrit :

          > Cristina commented: “Hi Arnaud, The Angular2Boot tutorial is so cool! I’ve > just got to the point where I see the application running at > http://localhost:8080/ Now I’d like to insert, just after the title, a > GWT widget created with UIBinder (an ui.xml file) and using an Event” >

  10. Been a java developer for 10 years, java is already flowing in my blood, so GWT is my first choice for front-end web applications. But unfortunately, it’s not that popular, and now i am trying Angular2+TypeScript as it looks more sense to java folks.

  11. biggest problem now is that all tutorials are spoiled by NodeJS/JavaScript on a server side (who needs this??)
    i want to learn Angular2, but i want to use Java (Spring/SpringMVC/Jersey etc.)

    1. So try that http://lteconsulting.fr/angular2boot/, you will both learn Angular 2 and code in Java 8. If you go to the “Getting started” page (http://lteconsulting.fr/angular2boot/tutorial/) you have the same tutorial as the one on the official typescript angular 2 page, but it is translated to Java, so no NodeJS/Javascript pollution there…
      The backend uses SpringBoot so you should be happy with that 😉
      I am really interrested in your feedback if you try it!
      Thanks

      1. project doesn’t work. browser can’t find angular2gwt.nocache.js resource. should i configure something ?

        and also i see error:
        ApplicationComponent_AngularComponent cannot be resolved in Application.java:

        Angular.bootstrap( ApplicationComponent_AngularComponent.get() );

        1. I guess you use eclipse and didn’t install the m2e-apt extension.
          To get the nocache.js file loaded you need to run the mvn gwt:run-codeserver.
          Maybe try to follow the angular 2boot tutorial…
          Thanks

  12. I know you are Java’s companion team and got a ton of enterprise level experience. Any chance you suggest any other alternate on backend instead of Java with angular 4 to 7 e.g. node.js or Go Lang or anything else.

    Do you see a benefit of doing full stack javascript? Entire team work on one language instead of spend sometime on the typescript/angular (keep up with constant changes) and take care of Java’s space as well.

    Thanks,
    Kavin

    1. I like Node.js. It’a production-grade solution that would allow you to use the TypeScript. IMO it’s beneficial to use the same language for front- and back end development in the enterprise setup. For more demanding back end system using Go might be an alternative to Java, but keep in mind that the Go community is rather small, and if you’ll run into an issue, StackOverflow may not have an answer. In the Enterprise setup, where you have a team with different skill level, Java is safer than Go.

      1. Thanks for your reply. We are going with Angular 4 & Hapi.js (coming from Walmart lab & managed black Friday traffic) for prototyping. If I like anything after working on Java, it is GO but Google is unpredictable (let go GWT). Go is not tested on the web front, so we will pass it. Google has promised with roadmap until Angular 7 and hopefully bigger community support forces them to stay on course.

        Thanks,
        Kavin

  13. Hello Yakov,
    I am doing web & mobile app development using Java. Right now, Java is used mostly for back end development and doesn’t have a popular front end framework. JS is front end language with a ton of frameworks but never liked language itself. Typescript as a language is pretty good but angular 4 with TS is over complex (at least to me).

    My search to learn a new front end framework took me to AngularDart (thought google abandon it). In fact, they are redesigning AdSense (money making) after six years in AngularDart (moving from GWT). I like dart from the word go, and dependency is defined in one file (few packages like angular4-TS). Flutter is another mobile framework, which uses dart. They are building new mobile OS using dart.

    I believe dart is even easier for java developers compare to the typescript. I developed simple mobile app in flutter using a dart in one hour with almost no knowledge of dart. Google is using a dart, even before they jumped on to the typescript. They removed plugin required in browser & introduce new AngularDart 4.

    Just like to know your thoughts in case you looked at dart. My biggest issue is lacked of UI component library. Google material components are not ready for enterprise level app (no datagrid, file upload & many more).

Leave a comment