Angular 2 and I

So this week marks the beginning of my 3 1/2 week journey with angular 2. As of right now, it’s all bumpy. Angular 2 is different, and that’s okay!

But I’m getting beside myself, the purpose of tonights blog is to go over the basics of creating a very simple angular 2 component. Angular 2 lends itself to being more modular that Angular 1 and that is achieved through components. So let’s get started.

The first thing we have to do is import the component from the angular core module. So lets do that

import {Component} from '@angular/core';

Once we’ve done that now we have access to angular 2’s component decorator. Next we need to export a JS ES2015 class. We’ll do that like this.

import {Component} from '@angular/core';
export class AppComponent {}

So now we’re exporting the AppComponent class to be used throughout our app. Next we need to actually use the component decorator that we imported from angular. The component decorator is a way of attaching metadata to our AppComponent class and this is basically done via a JS object. Like so.

import {Component} from '@angular/core';
selector: 'my-app', //<my-app></my-app>
template : `
<h1>Angular 2</h1>
<p> My first component!</p>
export class AppComponent {}

The selector property there is what angular 2 will be looking for as it goes through the html file. That tag will look like


When it finds that it will replace it with the markdown in the template property.

So the way we get this working is we go to our html file and add the my-app tag and angular will replace it will what is in our template. Right? Well almost. We still need to do one more thing. We need to tell angular 2 where to start and to do that we need to bootstrap. It looks something like this.

import {bootstrap} from '@angular/platform-browser-dynamic';
import {AppComponent} from './app.component';

We import the bootstrap method and our AppComponent and then we call bootstrap with our component. This tells angular that our AppComponent is that root component and that it needs to start there. And that’s it, the application should run from there.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.