Angular 2.0

Pubblicato il - Ultima modifica il

Angular 2.0 is the version that follows AngularJS, one of the most widely used and adopted JavaScript frameworks used by millions of Web developers around the world. Angular 2.0 is only currently available as a developer preview, but it's rapidly evolving. Changes are happening so fast that some of the code parts or features described might not work after three to four months since the framework is likely to have changed by then.

Angular 2.0 applications can be developed using ES5 and ES6 (check this article for new ES6 features), but it also includes support for Dart and TypeScript. In this article, you'll see a sample application written in TypeScript.

First, you need to make sure you have installed Node.js and NPM. After these have been set up, you need to install the TypeScript compiler and the TypeScript type definitions for Angular 2.0. You can install these using the following commands:

npm install -g tsc # the typescript compiler
npm install -g tsd # a tool which can install type definitions (.d.ts extension) for modules
tsd install angular2 # install the type definition for angular 2

As an example, let's create an application that displays Renaissance-era paintings and its related information. The app will look like the one displayed in the picture:

Angular 2.0 sample application

For styling, we'll be using bootstrap. Each image is displayed with its title, the painter's name, an image of the painting, and a short description. All this information will be in a TypeScript class:

class PortfolioItem {
   painterName:string;
   imageSrc:string;
   title:string;
   description:string;
   constructor(painterName, imageSrc, title, description) {
       this.imageSrc = imageSrc;
       this.title = title;
       this.painterName = painterName;
       this.description = description;
   }
}

The class is called PortfolioItem with four properties (these are self-explanatory) and a constructor that receives four parameters as well.

In Angular 2.0, the application is built differently compared to one that's built using Angular 1.x, which means that there's a class which is annotated. Based on these annotations, the Angular 2.0 framework will wire the logic and variables in the class to the ones defined in a template or directive.

@Component({
   selector: 'portfolio'
})
@View({
   templateUrl: 'portfolio.html',
   directives: [NgFor]
})
class PortfolioContainer {
   items: Array<PortfolioItem[]>;
   constructor() {
       this.items = [];
       this.fetchImages(this.items);
   }
   private fetchImages(container: Array<PortfolioItem[]>): void {
      ...
   }
}

bootstrap(PortfolioContainer);

The @Component annotation defines what HTML tag (attribute) should be mapped to this class. In this case, the selector defined for the PortfolioContainer class is portfolio, which means that here should be a tag called <portfolio> somewhere in the markup code. When the Angular 2.0 framework parses the HTML code, it maps the <portfolio> tag to this class and executes it's logic.

The @View annotation holds all the necessary information related to the HTML markup. In this case, it's the templateUrl it's loaded from and the array of angular directives that are used in that template. This sample only uses the NgFor directive, so the array only contains one item.

The class is fairly simple, as it has one member (items) under PortfolioItem arrays, a constructor, and a fetchImages method that loads up the items array with the relevant information about the images.

The last line of the app.ts file is the so called “main” method of Angular 2.0. The bootstrap method will take the class passed to it and it will build up the whole Angular 2.0 environment, bindings, and hooks using the information provided in the @Component and @View annotations.

The code for the template is the following:

<div class="row" *ng-for="#portfolioContainer of items">
   <div class="col-sm-6 col-md-4" *ng-for="#portfolioItem of portfolioContainer">
       <div class="thumbnail">
           <img src="{{ portfolioItem.imageSrc }}" >
           <div class="caption">
               <h3>{{portfolioItem.title}}</h3>
               <h5>{{portfolioItem.painterName}}</h5>
               <p>{{portfolioItem.description}}</p>
           </div>
       </div>
   </div>
</div>

There are two ng-for directives in the template. The first one iterates over the items array (which holds PortfolioItem arrays), while the second one creates a new thumbnail image, title, painterName and description for the PortfolioItems. The syntax of the ng-for directive in Angular 2.0 is similar to the one in Angular 1.x.

The main page which holds the <portfolio> tag looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
   <link rel="stylesheet" href="app.css"/>
   <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
   <script src="https://github.jspm.io/jmcriffey/bower-traceur-runtime@0.0.90/traceur-runtime.js"></script>
   <script src="https://jspm.io/system@0.16.js"></script>
   <script src="https://code.angularjs.org/2.0.0-alpha.30/angular2.dev.js"></script>
   <title>Angular 2.0</title>
</head>
<body>
   <nav class="navbar navbar-inverse navbar-fixed-top">
       <div class="container">
           <div class="navbar-header">
               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                   <span class="sr-only">Toggle navigation</span>
                   <span class="icon-bar"></span>
                   <span class="icon-bar"></span>
                   <span class="icon-bar"></span>
               </button>
               <a class="navbar-brand" href="#">Angular 2.0</a>
           </div>
       </div>
   </nav>
   <div class="container">
       <div class="portfolio">
           <portfolio></portfolio>
       </div>
   </div>
   <script>System.import('app');</script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>

It is a normal HTML5 file, which references to bootstrap CSS files, angular2 source files and its dependencies in the <head> section. In the <body> section, there is a navigation panel defined as a classic bootstrap navigation bar. Inside the <body> tag you have the <div> with the class name portfolio and inside that you have the <portfolio> tag, which is where the template processing will happen and the HTML code generated by the Angular 2.0 framework will be inserted.

There is another important part in the page that imports the script named "app", System.import('app'). This is what loads the app.js file. The app.js file is created by the TypeScript compiler and generates normal JavaScript code. In this case, it's shown using the require.js / AMD structure to define dependencies between JavaScript modules.

define(["require", "exports", 'angular2/angular2'], function (require, exports, angular2_1) {
   var PortfolioItem = (function () {
       function PortfolioItem(painterName, imageSrc, title, description) {
           this.imageSrc = imageSrc;
           this.title = title;
           this.painterName = painterName;
           this.description = description;
       }
       return PortfolioItem;
   })();
   var PortfolioContainer = (function () {
       function PortfolioContainer() {
           this.items = [];
           this.fetchImages(this.items);
       }
       PortfolioContainer.prototype.fetchImages = function (container) {
		...
       };
       PortfolioContainer = __decorate([
           angular2_1.Component({
               selector: 'portfolio'
           }),
           angular2_1.View({
               templateUrl: 'portfolio.html',
               directives: [angular2_1.NgFor]
           })
       ], PortfolioContainer);
       return PortfolioContainer;
   })();
   angular2_1.bootstrap(PortfolioContainer);
});

Angular 2.0 is still heavily under development, but the community and the builders are trying to resolve all the issues that were discovered and reported by developers for Angular 1.x. Angular 2.0 has some major performance benefits compared to Angular 1.x, mainly in cases where you want to use other non-angular based extensions and plugins with their own binding or template engines.

Pubblicato 23 luglio, 2015

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Prossimo Articolo

The Web Developer's Checklist