You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Angular 2 is in active development right now, but is still in an alpha state. In fact, at the time of writing this article, the alpha 31 release was just cut. There are a lot of things in flux, but the platform has enough meat on it that you can start playing with it, and see just what the next version of Angular has to offer.
4
+
5
+
**And that is exactly what we are going to do; build a small application using Angular 2.**
6
+
7
+
##Getting Started
8
+
9
+
***Note:*** *I happen to be using ASP.Net 5, but the server portion of this example is largely irrelevant.*
10
+
11
+
There are several different ways you can get started with the Angular 2 bits, but the easiest way is to simply use the bundles hosted on https://code.angularjs.org/.
12
+
13
+
That's exactly what we are going to do.
14
+
15
+
In our main page, we need to include the following script tags at the bottom of the page in order to get up and running with Angular 2.
You will notice that the first two things we import are the Traceur Runtime and System.js. These are basically polyfills that allow us to use some ES6 features in the browser despite their not being implemented yet.
32
+
33
+
System.js gives us module loading, which aligns really nicely with ES6 and TypeScript.
34
+
35
+
##Setting The Stage
36
+
37
+
Angular 2 is all about embracing components. That means we need to start thinking about our application as a tree of components, rather than a disconnected set of controllers and views.
38
+
39
+
Every tree has a root, and our application is no exception. We want to load our application right into the page by dropping in some kind of component that will represent the entry point of our application.
40
+
41
+
```html
42
+
<!DOCTYPE html>
43
+
<html>
44
+
<head>
45
+
<!-- head stuff -->
46
+
</head>
47
+
<body>
48
+
49
+
<contact-manager>
50
+
51
+
<h1>Loading...</h1>
52
+
53
+
</contact-manager>
54
+
55
+
<!-- scripts -->
56
+
</body>
57
+
</html>
58
+
```
59
+
60
+
You can see we are dropping in our custom `<contact-manager>` component directly into the body of the page. When our application bootstraps, this is where we want it to go. The `<h1>Loading...</h1>` we put right into the middle is just temporary content. When the real component loads, anything inside that tag will get replaced.
61
+
62
+
##Application Structure
63
+
64
+
Our application structure is actually going to be really simple for now, basically in our root folder we are going to have an `app` folder where our Angular application will reside.
65
+
66
+
```
67
+
wwwroot
68
+
│ index.html
69
+
│
70
+
└───app
71
+
│ contact-manager.ts
72
+
```
73
+
74
+
##The Application Component
75
+
76
+
Obviously we haven't actually created our `contact-manager` component yet, so let's go ahead and do that.
77
+
78
+
```typescript
79
+
import {Component, View, bootstrap} from 'angular2/angular2';
80
+
81
+
@Component({
82
+
selector:'contact-manager'
83
+
})
84
+
@View({
85
+
template:'<h1>Welcome to {{title}}</h1>'
86
+
})
87
+
export class ContactManager {
88
+
title:string;
89
+
90
+
constructor(){
91
+
this.title = "Contact Manager";
92
+
}
93
+
}
94
+
95
+
bootstrap(ContactManager);
96
+
```
97
+
98
+
This is about as simple a component as we can possibly get, but there are several interesting and new things going on here, so let's dig through them one by one.
99
+
100
+
###ES6 Module Imports
101
+
102
+
Even though I am using TypeScript in this example *(Angular 2 is being written in TypeScript)*, everything you see, with the exception of the `:string` type annotation, is pure ES6/7. The `import` keyword, is pulling in dependencies from the Angular 2 bundle so I can create and bootstrap my component.
103
+
104
+
###Decorators
105
+
106
+
Decorators are the funny `@foo` syntax you see in the code, and they are a [new proposal for ES7](https://github.com/wycats/javascript-decorators). The good news is that decorators are essentially just functions that can modify the thing that they decorate.
107
+
108
+
>A decorator is:
109
+
>
110
+
>an expression
111
+
>that evaluates to a function
112
+
>that takes the target, name, and property descriptor as arguments
113
+
>and optionally returns a property descriptor to install on the target object
In this instance, `@Component` and `@View` are ways of adding meta-data to the class that Angular will use to find, and load our component into the DOM. For instance, `selector:'contact-manager'` is the CSS selected that angular will use to locate our component. While a `@Component` is limited to being only an element, there is also a `@Directive` decorator that can take advantage of a larger range of CSS selectors. This is a much simpler model than Angular 1, and provides a far greater degree of control.
118
+
119
+
For example, if you wanted to match only a `div` with an attribute `name`, that had a specific value of `josh`, *and* had the CSS class `crazy-selector`, your selector would look like this:
120
+
121
+
```typescript
122
+
@Directive({
123
+
selector: 'div[name=josh].crazy-selector'
124
+
})
125
+
```
126
+
127
+
The markup for something so crazy would look like this:
<div name="josh" class="crazy-selector">This will get matched</div>
132
+
133
+
<div class="crazy-selector">But not this</div>
134
+
```
135
+
136
+
###Classes
137
+
138
+
You may have heard that controllers were going away in Angular 2, but that really isn't true. It's more accurate to say that all **components** and **directives** are essentially just controllers with some meta-data.
139
+
140
+
In our simple little application, our controller is using the new `class` syntax from ES6. This doesn't mean that you *have* to use classes. At the end of the day, it is just syntactic sugar over constructor functions and `prototype`... so you could write this same thing in ES5.
141
+
142
+
```typescript
143
+
export class ContactManager {
144
+
title:string;
145
+
146
+
constructor(){
147
+
this.title = "Contact Manager";
148
+
}
149
+
}
150
+
```
151
+
152
+
What you don't see in here is any sort of `$scope` construct. That's because in Angular 2, data binding happens directly against the component, and there is no intermediary that you have to deal with.
153
+
154
+
###Bootstrapping
155
+
156
+
The last thing we need to do is actually bootstrap our application by telling Angular which component to use as the root. That's this little bit of code here:
157
+
158
+
```typescript
159
+
import {Component, View, bootstrap} from 'angular2/angular2';
160
+
161
+
//Snip...
162
+
163
+
//load our component into the DOM
164
+
bootstrap(ContactManager);
165
+
```
166
+
167
+
Notice there are no funky magic strings to deal with here... just a concrete instance of our `ContactManager` component. Angular will look for the specified `selector` in the DOM and bootstrap our application by loading the component into the element that matches.
168
+
169
+
**Pro Tip:** `bootstrap` returns a promise that you can use to log information out to the console in case your application fails to load. It will help with debugging, or even displaying a friendly error message to the user.
170
+
171
+
```typescript
172
+
bootstrap(ContactManager)
173
+
.then(app => {
174
+
console.log('Bootstrap Successful');
175
+
}, err => {
176
+
console.error(err);
177
+
});
178
+
```
179
+
180
+
##Compiling The TypeScript
181
+
182
+
Since we are using TypeScript, we can't just send that down to the browser and expect it to work. Well... we could actually use the TypeScript transpiler directly with System.js to compile the TypeScript files directly in the browser, but I want to walk through using the compiler directly.
183
+
184
+
The first step is to install the compiler, which you can do with **npm**. In this case we actually want to use 1.5, but it is still in beta, so you can use this command to install it globally.
185
+
186
+
```
187
+
npm install -g typescript@1.5.0-beta
188
+
```
189
+
190
+
**Important: ** Once you have it installed, make sure you are actually running the correct version by using this command.
191
+
192
+
```
193
+
tsc -v
194
+
```
195
+
196
+
**Important: ** If you don't see `message TS6029: Version 1.5.0-beta` printed on the commandline, then you may have a previous version of TypeScript installed in your `PATH` environment variable, that you will need to manually remove. This is pretty typical if you have been using Visual Studio, so just be aware.
197
+
198
+
###TypeScript Definition Files
199
+
200
+
In order for TypeScript to figure out how to interpret the `angular2/angular2` stuff, especially the annotations, we need to give the compiler a little bit of help. This is achieved through what are called [TypeScript Definition Files](http://www.typescriptlang.org/Handbook#writing-dts-files). Simply put, they are meta-data files that describe the public API of a library like **jQuery** or in this case, **Angular 2**.
201
+
202
+
***Where do you get these files?***
203
+
204
+
There is an entire repository of them up on a [GitHub project called DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped), and luckily the creator has put together a utility called `tsd` to pull these files into your project that works much like `npm`.
205
+
206
+
You can get detailed information on [the official tsd site](http://definitelytyped.org/tsd/), but all we really need to do for now is install the utility using npm, and then use it to install the **angular2** definition files.
207
+
208
+
```
209
+
npm install tsd -g
210
+
tsd install angular2 --resolve --save
211
+
```
212
+
213
+
This will create a `/typings` folder in your project that you can later reference in order to let TypeScript know about all your dependencies. There are a couple of difference ways to do this, but for now you can simply put this special reference comment at the top of your `contact-manager.ts` file.
214
+
215
+
```typescript
216
+
/// <reference path="../typings/tsd.d.ts" />
217
+
import {Component, View, bootstrap} from 'angular2/angular2';
218
+
```
219
+
220
+
###Compiling With tsc
221
+
222
+
Once you have your definition files, and the compiler, you can run it against your application folder. There are several options we need to pass into the compiler, so instead of doing that on the commandline, TypeScript 1.5 allows us to create a special file called `tsconfig.json` where it will read the compiler options from.
223
+
224
+
As an added benefit, if we stick this file into our `/app` directory, then TypeScript will compile all the files in that directory unless we tell it otherwise.
225
+
226
+
For detailed information you can read the [specifications for the `tsconfig.json` file](https://github.com/Microsoft/TypeScript/wiki/tsconfig.json).
227
+
228
+
The TypeScript compiler config file for this project looks like this:
229
+
230
+
```json
231
+
{
232
+
"compilerOptions": {
233
+
"target": "ES5",
234
+
"module": "commonjs",
235
+
"sourceMap": true,
236
+
"emitDecoratorMetadata": true,
237
+
"watch": false,
238
+
"removeComments": true
239
+
}
240
+
}
241
+
```
242
+
243
+
Now we can compile all our `.ts` files from the commandline with this command:
244
+
245
+
```
246
+
tsc --project .\app
247
+
```
248
+
249
+
##Loading The Application
250
+
251
+
Now that we have compiled our TypeScript down into JavaScript, the final piece we need to make this all work, is to load our application resources into the browser.
252
+
253
+
Because the application is using ES6 style module syntax, we are going to use [System.js as our module loader](https://github.com/systemjs/systemjs).
254
+
255
+
The magic that makes it all happen is this tiny little script block that we need to stick at the very bottom of our page. It tells System.js where our application code lives, and then loads our root contact manager component into the browser. **If there were any other dependencies, System.js would take care of loading them in for us.**
256
+
257
+
```html
258
+
<body>
259
+
260
+
<contact-manager></contact-manager>
261
+
262
+
<!-- Other scripts: Traceur, System, Angular2 -->
263
+
264
+
<!-- Application Bootstrap -->
265
+
<script>
266
+
System.config({
267
+
baseURL: '/app'
268
+
});
269
+
270
+
System.import('contact-manager');
271
+
</script>
272
+
</body>
273
+
```
274
+
275
+
**Magic!**
276
+
277
+
Now when we load the page up, we should **"Welcome to Contact Manager"** in big bold text on the screen.
278
+
279
+
##Conclusion and Next Steps
280
+
281
+
Alright, so that isn't exactly impressive, but **stay tuned for the next installment where we dig into the new data binding syntax** and begin to see where Angular 2 really shines.
282
+
283
+
The full source code can be found here as well as the contents of this article in markdown format:
0 commit comments