Angular 2 — Our first component (updated: using Beta 15)
In my first article we spoke about setting up the working environment for using Angular 2 and therefore it is important to have followed these steps before progressing to the “next steps” in this article. If you missed the first article you can always go here or you can follow the official guide if you want to set up an Angular 2.0
Let’s create something really simple and basic to begin with, only because it is very important to understand all the steps. We can then progress to something that involves more work, like creating an app using all the CRUD operations, sub-components, services, pipes, directives, using dependency injection, structural directives, interpolation, property binding, event binding, variable declarations, forms, routing, etc, etc.
Related Links:
. Setting up the working environment
You can download the code discussed in this blog from my GitHub.
Steps:
- Let’s go! — Our first component
- Bootstrapping the app
- Creating the index.html
- Running our first component
1. Let’s go! — Our first component
If you have the working environment already set up, your project should look like this:
As you can see we have a project set up; I am using Visual Studio Code. Now we are ready to create our first simple component. To do this, create a new file called app.component.ts
It is important to have some knowledge about typescript language and the best place to acquire this knowledge is here.
What’s a component?
A component is a combination of a view (the template) and some logic (our Typescript class .ts extension)
Let’s first create a class inside our app.component.ts:
export class AppComponent {
constructor() {}
}
All classes in TypeScript have a constructor, whether you specify one or not. If you do not define the constructor, the compiler will automatically add one. The constructor is called before any other component lifecyle hook. If the component has any dependencies, the constructor is the best place to inject those dependencies. The export statement tells TypeScript that this is a module whose AppComponent class is public and accessible to other modules of the application.
More about lifecycle hook on Angular 2.
In Angular 2, components are the main way we build and specify elements and logic on the page, whilst in Angular 1 we can achieve this using controllers and scope; using Angular 2 all those concepts are combined into Components. Components are hierarchical way, so Angular 2 applications always start with one main component.
To identify to Angular that there is a component, we use the @Component decorator and to be able to use it, we have to import it:
import {Component} from 'angular2/core';@Component()
export class AppComponent{
constructor() {}
}
The @Component decorator takes a required configuration object with the information Angular needs to create and present the component and its view.
….we’re not finished yet!
The @Component decorator is expecting only one property called: selector. The selector tells Angular what to look for in the HTML pages. Every time the selector is found in the HTML, Angular replaces it with our component. Let’s add the selector to our component:
import {Component} from 'angular2/core';@Component({
selector: 'main-app'
})
export class AppComponent{
constructor() {}
}
Every time our HTML contains the element like:
<main-app></main-app>
….Angular will instantiate a new instance of the class AppComponent.
….and it is still not finished!
Previously we said…
“A component is a combination of a view (the template)”
So, a component must have a template where you can inline it, or we can externalise the template in another file (using templateUrl), but for the moment let’s keep it simple.
import {Component} from 'angular2/core';@Component({
selector: 'main-app',
template: '<h1>Hiya! First Component</h1>'
})
export class AppComponent {
constructor() {}
}
We tell Angular that AppComponent is a component by attaching metadata to the class and the metadata tells Angular how to process a class.
2. Bootstrapping the app and loading components
The bootstrap method (available on Angular 2) is a subject that would take too long to write about now, therefore we will keep things simple at this stage. I address this subject in more detail here.
We need to start our app and the bootstrap method will help us to get the job done. We have to import it from angular2/platform/browser module using a different location (not angular2/core for example) because Angular 2 supports server-side rendering or running in a Web Worker. Let’s create a new file called: boot.ts to separate the bootstrap logic.
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';bootstrap(AppComponent)
.then (success => console.log('Bootstrap successfully!'))
.catch(err => console.log(err));
A bit of background…
The bootstrap method is a promise object and the first parameter we define is the main class of our app - the component; that’s why we had to import {AppComponent} from './app.component’.
We were able to import this class because we used the ’export’ keyword which makes the class public across the project. As per the example above, inside the brackets {} is the name of our class and from ‘’ is where the file of that class is located. Because we have all the files in the main root we don’t need to include any folder or sub folder to locate the component (ex: ‘. /app/app.component’). At the moment we do not need to worry about the folder structure because it is a basic example; however, the second parameter of the bootstrap method is where we can have an array that contains a list of what we want to make available for injection.
The import statement tells the system it can get an AppComponent from a module namedapp.component located in a neighboring file. The module name (AKA module id) is often the same as the filename without its extension.
3. Creating the index.html
Create another file named: index.html and add the following html:
<html><head>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script><script src="node_modules/systemjs/dist/system.js"></script> <script>
System.config({
defaultJSExtensions: true,
map: {
'angular2': 'node_modules/angular2',
'rxjs': 'node_modules/rxjs'
}
});
System.import('built/boot');
</script></head><body>
<main-app>Loading…</main-app>
</body></html>
In Angular 1.x adding scripts to our HTML files was simple, we just needed to add a script for angular.js, and a script for every JS file we wrote. Angular 2 is bundled in modules, and these modules can be loaded dynamically. To load our module we are relying on a tool SystemJS which is a small module loader. We added it statically into our HTML and it tells where the modules are located in our server. It then automatically figures out the dependencies between modules and downloads the ones used from our application.
System.import('built/boot');
‘build/boot’ — Indicates where is located our boot.js and if you did not change your tsconfig.json, you should not have any problems loading the JS file.
4. Running our first component
We are pretty much done! Hooray! We only need to run our first component using Angular 2.
Open the cmd (command prompt) and go to your project directory and type: npm run app
Before loading the scripts you should be able to see “Loading…”
…and then the application should show “Hiya! First Component”
If you open the developer tools from your browser, you should be able to see the console.log(‘Bootstrap successfully’) message…