Angular 2 Easiest Quickstart Tutorial

No ng-app in Angular 2

In Angular 2 instead of something like ng-app you actually start with application level component which you define yourself, I am going to call my top level component my-app.

App/index.html

<html>
<head>
    <title>Angular 2 QuickStart</title>
    <script src="https://jspm.io/system@0.19.js"></script>
    <script src="https://code.angularjs.org/2.0.0-alpha.47/angular2.dev.js"></script>
    <script>
        
        System.import('./myapp');
    </script>
</head>
<body>
<my-app></my-app>
</body>
</html>

To make it work let's write an appropriate code in myapp.ts.

Let's create a Class called MyApp but first we need to import bootstrap function from angular 2, we also need to import two more decorators Component and View, these decorators are ways to add behaviour or features to the class we have 
created.

import {bootstrap, Component, View} from "angualr2/angular2";

Class MyApp {

}

We need to use these decorators above the MyApp Class and we do it by prefixing @ symbol and pass an object where we can define specific properties.

Let's write Component decorator first and define selector property, selector property tells angular 2 that this class deals with given component( in this case my-app ).

@Component({
	selector : 'my-app', // this my-app is the same top level component my-app in that we decleared in html 
});

Now Let's write View decorator and define template property, in template property we can write our Html template which our component will finally display after rendering.

@View({
	template : `
		<div>
			<h1>{{ message }}</h1>
		</div>
	`
});

Note: I am using tick(`) not a single quote(') for multi-line string.

Now let's add message property in our MyApp class and initialize in the constructor.

Class MyApp {

	message : string;

	constructor() {
		this.message = 'Hello Angular 2';	
	}

}

Let's finally call a bootstrap function and pass our MyApp class to bootstrap our app.

bootstrap(MyApp);

So our final file structure should look something like this,

App/myapp.ts

import {bootstrap, Component, View} from "angular2/angular2";

@Component({
	selector : 'my-app'
})
@View({
	template : `
		<div>
			<h1>{{ message }}</h1>
		</div>
	`
})
class MyApp {
	
	message : string;
	
	constructor( ) {
		this.message = 'Hello Angular 2';	
	}
}

bootstrap(MyApp);

Note: Our Html file looks for the myapp.js file so don't forget to compile myapp.ts before serving the app

Now you should see Hello Angular 2 in the browser.

That's it, guys, I will start writing about Angular 2 from now on as Angular 2 release is getting closer and less likely to have any major changes in the API.

Something to say? Tell us in comment section.