Buscar
Cerrar este cuadro de búsqueda.

Angular2 – What is it?

Raona

Raona

| 2 febrero, 2016

Angular 2. What is it? How can I use it with Visual Studio 2015?

Angular 2 is a renovated framework for Single-Page Applications (SPA) development. Developed in TypeScript, it is the clear evolution of AngularJS 1, and as such, still using a functional architecture similar to its predecessor.
Image 1: Basic architecture of Angular 2

Some concepts have been left behind like controllers and scope, among many other aspects that have been replaced by simple classes, and a metadata system has been implemented to define how Angular will process each of the classes.
A simple Angular 2 class example:
alt text

This creates a Component that Angular will inject to the HTML by placing the tag . If you have in mind AngularJS 1, controllers have become directives.
In this article I will explain how to configure VS2015 to use Angular2.

Creating an Angular2 project in VS2015

The following steps are based on «5 min Quickstart» (https://angular.io/docs/ts/latest/quickstart.html) and “Angular2 with TypeScript using Visual Studio 2015” http://www.codeproject.com/Articles/1070022/Angular-with-TypeScript-using-Visual-Studio.

First you need to install ASP.NET 5 RC1 (https://download.microsoft.com/download/B/0/A/B0AEBD7D-6979-4265-B1AC-A0B73618FB22/AspNet5.ENU.RC1_Update1.exe).

Once installed, open VS2015 and create an ASP.NET Web Application project. I named it Angular2Weather.
alt text

Then we have to choose what kind of template we want. In our case, we have to choose the Empty option in ASP.NET 5 Templates category.
alt text

Once we have the solution created, we need to add a new dependency to be able to use our static files like HTML, CSS, JavaScript… To do this, open the file project.son and change the dependencies keys to:

"dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
  },

We also need to change the Configure method of Startup.cs file:

public void Configure(IApplicationBuilder app)
{
      app.UseDefaultFiles();
      app.UseStaticFiles();
}

Now we need to download Angular 2 and all of its dependencies. Go to our project and add a new Client-side NPM Configuration File with the name package.json.
alt text

Within this file put the following code:

{
  "name": "Angular2Weather",
  "version": "1.0.0",
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrent "npm run tsc:w" "npm run lite" "
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.0",
    "systemjs": "0.19.6",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.10"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^1.3.2",
    "typescript": "^1.7.5",
    "gulp": "^3.9.0",
    "del": "^2.1.0"
  }
}

It will start to download the necessary files from NPM. Once completed, we will create a new client-side file of type TypeScript JSON Configuration File with the name tsconfig.json, and the following content:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "wwwroot/app"
  },
  "exclude": [
    "node_modules"
  ]
}

This is the TypeScript compiler configuration compatible with Angular 2.

Then, we will create another client-side file, this time inside the /wwwroot folder. The file type will be HTML Page and his name index.html.

Now the solution should look like this:

alt text

The next step, is to copy the necessary .js files downloaded from NPM to the /wwwroot directory. To do this we will create a new client-side file Gulp Configuration File with the name: gulpfile.js. Gulp is a system that allows you to run scripts to do automatic tasks such as copy files, minify javascript, etc. This file should contain:

/// <binding BeforeBuild='build' Clean='clean' />
const gulp = require('gulp');
const del = require('del');

gulp.task('clean', function () {
    return del('wwwroot/scripts/**/*');
});

gulp.task('compile:deps', ['clean'], function () {
    return gulp.src([
      'node_modules/es6-shim/es6-shim.min.js',
      'node_modules/angular2/bundles/angular2-polyfills.js',
      'node_modules/angular2/bundles/angular2.dev.js',
      'node_modules/rxjs/bundles/Rx.js',
      'node_modules/systemjs/dist/system.js',
      'node_modules/systemjs/dist/system-polyfills.js',
    ]).pipe(gulp.dest('wwwroot/scripts/angular2'));
});

gulp.task('build', ['compile:deps']);

As you can see on the first line, this script will execute the build task before compiling the project and when we do a project clean it will delete all content inside /wwwroot/scripts.
Now let’s make a rebuild of the solution and all JS needed will appear in /wwwroot/scripts.
Then open index.html and insert the following content:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>

    <script src="scripts/angular2/es6-shim.min.js"></script>
    <script src="scripts/angular2/system-polyfills.js"></script>
    <script src="scripts/angular2/angular2-polyfills.js"></script>
    <script src="scripts/angular2/system.js"></script>
    <script src="scripts/angular2/rx.js"></script>
    <script src="scripts/angular2/angular2.dev.js"></script>

    <script>
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            }
        });
        System.import('app/main')
              .then(null, console.error.bind(console));
    </script>
</head>
<body>
    <my-app>Loading...</my-app>
</body>
</html>

System.config is the configuration method of SystemJS, in our case, packages allows us to define how it should resolve a petition of a module that is inside the folder /app.

Now we are going to create the component that we have put in the index.html.

Create the /app folder in /wwwroot. Inside /wwwroot/app create two new files, app.component.ts and main.ts.

The app.component.ts file content should be the following:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }

And the main.ts, which is responsible for loading the needed platform components where the instance will run. We must bear in mind that Angular 2 is compatible with Apache Cordova or NativeScripts, which means not only is used to develop web pages for desktop browsers.
The content of main.ts will be:

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component'

Run the solution and we should see this:
alt text

Conclusion

Angular 2 is still in beta, but it should not change too much until the final version comes out. Also you can follow the changes of each version here: https://github.com/angular/angular/blob/master/CHANGELOG.md

The next article will teach you how to start developing a real application in Angular 2. I recommend you to read the developer guides of Angular 2 which can be found at: https://angular.io/docs/ts/latest/guide/

More information

Contact us

Raona

Compartir en Redes Sociales