The best way to learn angular 2, is to create an example Angular 2 application from scratch. The AngularJS (Angular 1 ) application was very easy to create and start. But in case of Angular 2, you need to set up lots of configuration files and libraries before getting up and running
In this tutorial let us learn how to create a simple angular 2 application from scratch. If you are new to angular 2 you should look at the Introduction to Angular 2 and Installing and getting started with Angular 2 Tutorials.
There are many possible scenarios, by which you can create Angular 2 Application. We have discussed few of them in this following tutorial
Table of Contents
How to Create Angular 2 Application Using SystemJS
In this tutorial, we are going to build a simple application for an ABC Bank Ltd. which just displays “Hello & Welcome to ABC Bank Ltd. “
Setting up an Angular 2 Application
The Setting up and angular 2 application requires the following steps
- Create an Application folder
- Create Configuration file
- Install Angular 2 , Typescript, System.JS and other dependencies
- Create First Component
- Create a root Angular module
- Bootstrap our application
- Create the index.html
- Run the application
1. Create an Application Folder
Open a command prompt and create a folder GettingStarted. Then open Visual Studio Code and open the folder
2. Create Configuration file
Before we start to code, we need to configure the npm, Typescript & System.JS. We discussed these topics in our previous tutorial Installing and getting started in Angular2
NPM Configuration file ( Package.json )
Package.json file contains the metadata about modules required for our Angular Application. It contains a list of external dependencies that are used in our application. The npm ( node package manager) uses these files to install the required dependencies.
The Sample Package.json is listed below. Create file named Package.json in the root folder and copy the following content
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | { "name": "abc-bank-ltd", "version": "1.0.0", "scripts": { "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ", "lite": "lite-server", "postinstall": "typings install", "tsc": "tsc", "tsc:w": "tsc -w", "typings": "typings" }, "license": "ISC", "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/core": "2.0.0", "@angular/forms": "2.0.0", "@angular/http": "2.0.0", "@angular/platform-browser": "2.0.0", "@angular/platform-browser-dynamic": "2.0.0", "@angular/router": "3.0.0", "@angular/upgrade": "2.0.0", "core-js": "^2.4.1", "reflect-metadata": "^0.1.3", "rxjs": "5.0.0-beta.12", "systemjs": "0.19.27", "zone.js": "^0.6.23", "angular2-in-memory-web-api": "0.0.20", "bootstrap": "^3.3.6" }, "devDependencies": { "concurrently": "^2.0.0", "lite-server": "^2.2.2", "typescript": "^2.0.2", "typings":"^1.3.2" } } |
Typescript Configuration file
Typescript requires two configuration files. One is tsconfig.json, which must be present in the root folder. The second file is typings.json which contains the Typescript definition file
Goto to the root folder of the project and create the tsconfig.json file. Copy the following content
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false } } |
Next, create the typings.json file and copy paste the following
1 2 3 4 5 6 7 8 9 | { "globalDependencies": { "core-js": "registry:dt/core-js#0.0.0+20160725163759", "jasmine": "registry:dt/jasmine#2.2.0+20160621224255", "node": "registry:dt/node#6.0.0+20160909174046" } } |
Systemjs.config.js (Module loader)
The Angular 2 Applications needs module loader to load the application & associates modules dynamically. This is done using the SystemJs. The SystemJs has its own configuration file, which it uses to load the application
Create Systemjs.config.js in the root folder of the application and copy the following.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | /** * System configuration for Angular 2 samples * Adjust as necessary for your application needs. */ (function (global) { System.config({ // paths serve as alias paths: { 'npm:': 'node_modules/' }, // map tells the System loader where to look for things map: { // our app is within the app folder app: 'app', // angular bundles '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', // other libraries 'rxjs': 'npm:rxjs', 'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api', }, // packages tells the System loader how to load when no filename and/or no extension packages: { 'app': { main: 'bank', defaultExtension: 'js' }, rxjs: { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { main: './index.js', defaultExtension: 'js' } } }); })(this); |
3. Install the Angular2 libraries, Typescript & SystemJs
The final step is to run the npm package manager to install the dependencies. Right click and select Open the Command prompt. You can also Open the command prompt directly and go to the root folder of the application
Type the following command
1 2 3 | npm install |
If the installation is successful, you will see the Node_modules & typings folders under the root folder. You may see many warning & errors ignore them. You can also run the npm installer again in case any issues.
If the typings folder does not appear then just run the following command in npm shell
1 2 3 | npm run typings install |
If you still face problems in installing then run the following command in npm shell
1 2 3 | npm cache clean |
Then try running the npm install again
4. Create your first Component
The next step is to create a Component file. First Create an App Folder under the root folder. Create bank.component.ts inside the app directory. Copy the following code
1 2 3 4 5 6 7 8 9 10 11 | import { Component } from '@angular/core'; @Component({ selector: 'bank-app', template: '<h1>Hello & Welcome to ABC Bank Ltd. </h1>' }) export class BankComponent { } |
The Component is the most important part of the angular 2. It controls the region of the screen or View. It consists of three main parts one is class, a class decorator, and an import statement
Component class
A component is a simple class. The class is defined using the Export keyword so that it can be used in other parts of the application
1 2 3 4 5 | export class BankComponent { } |
@Component decorator
The BankComponent class is then, decorated with @Component decorator attribute. The class decorator provides Metadata about the component class. The Angular uses this Metadata to create the view
1 2 3 4 5 6 | @Component({ selector: 'bank-app', template: '<h1>Hello & Welcome to ABC Bank Ltd. </h1>' }) |
The Metadata above has two fields. The selector & template.
Template
The template field is plain HTML that tells angular what to display. In the example, above it displays “Hello & Welcome to ABC Bank Ltd” inside H1 tag
Selector
The selector tells angular, where to display. In the example above selector is “bank-app”. The selector (bank-app) is replaced by the HTML template, when Angular renders the view.
Import
Since we are using the @Component decorator, we need to tell the Angular , where to find it. The @component decorator is available in @angular/core module. Hence we need to refer it our class. This is done using the import method. As follows.
1 2 3 | import { Component } from '@angular/core'; |
5. Create the root Angular Module
The Angular 2 applications are modular. Each feature of the application must be developed using small packets based on a feature and are grouped into modules. The every angular application must have at least one module called as root Module.
Create a file under the app folder with the name bank.module.ts. This is the main module of our application.
1 2 3 4 5 6 7 8 9 10 11 12 | import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class BankModule{ } |
First, create a BankModule class. Note that we are using the export keyword so that this module can be used in other modules. You can include any relevant codes in the class, but right now we leave it blank.
@NgModule
We need to tell angular that this class is an Angular Module. We can do this by decorating the class with @NgModule Decorator as shown below.
1 2 3 4 5 6 7 | @NgModule({ imports: [ BrowserModule ], declarations: [ BankComponent ], bootstrap: [ BankComponent ] }) |
@NgModule passes Metadata to angular by using the fields imports, declarations & bootstrap.
Imports Metadata tells angular, the modules required by this module. The BankModule requires BrowserModule
Declaration Metadata lists the components, directives , services etc that are part of this module. We have only one component in our example, hence we list it here.
Bootstrap Metadata identifies the root component for the module. Angular loads this component, when it loads the module. In our example, BankComponent must be loaded when the application is loaded. Hence that is listed here
6. Bootstrap our application
Now we need to tell angular to load our root module.This requires us to create another javascript module with the following code
1 2 3 4 5 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { BankModule } from './bank.module'; platformBrowserDynamic().bootstrapModule(BankModule); |
In the above code, we import platformBrowserDynamic . This function contains necessary methods to bootstrap the angular application. The bootstrapper must know the location of our BankModule. Hence in the next line, we import the BankModule. Finally, we invoke the bootstrapModule(BankModule) to start our BankModule Application
7. Create the Index.html
Finally, we need to create our root an HTML file, i.e. index.html. Create the index.html file in the root folder and copy the content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <html> <head> <title>Angular 2 Tutorial from TekTutorialsHub.com - Getting Started</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 1. Load libraries --> <!-- Polyfill(s) for older browsers --> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <!-- 2. Bootstrap --> <link href="node_modules/bootstrap/dist/css/bootstrap.css" rel="stylesheet" /> <!-- 3. Configure SystemJS --> <script src="systemjs.config.js"></script> <script> System.import('app').catch(function(err){ console.error(err); }); </script> </head> <!-- 4. Display the application --> <body> <div class='container'> <bank-app>Loading...</bank-app> </div> </body> </html> |
bank-app CSS Selector
You will see that we have added bank-app CSS Selector inside the body tag of our index.html
1 2 3 | <bank-app>Loading...</bank-app> |
This is where Angular 2 loads our application. Scroll back to and take a look at the bank.controller.ts. In the @Component decorator, we have used ‘bank-app’ in the selector field. The Html inside the template field is placed inside the ‘bank-app’ CSS selector inside the index.html
1 2 3 4 5 6 | @Component({ selector: 'bank-app', template: '<h1>Hello & Welcome to ABC Bank Ltd. </h1>' }) |
System.js
1 2 3 4 5 6 7 | <!-- 2. Configure SystemJS --> <script src="systemjs.config.js"></script> <script> System.import('app').catch(function(err){ console.error(err); }); </script> |
Note that we have loaded the SystemJs javascript. SystemJs is responsible loading the required javascript file required by our angular Application. This is done by invoking the import method and bootstrapping the SystemJS.
8. Run and Application
Finally, we are ready to roll. Right click on and select Open the command Prompt and enter the following command
1 2 3 | Npm start |
npm creates the instance of the lite server and loads the index.html in the browser. You will see “Hello & Welcome to ABC Bank Ltd” displayed.
Conclusion
We have successfully built our first angular 2 application. In the next tutorial, let us look at how Angular 2 Bootstraps works in little more detail.
Hello, we’ve used this tutorial years ago with success. We use SystemJS to load all needed source files and necessary imports to run our app from Visual Studio in IIS express, without the need of rebuilding after every code change. This worked until Angular 13 arrived. Angular 13/14 is distributed in a different module format and our current SystemJS configuration doesn’t work anymore. Tried everything using different transpilers etc, but nothing worked. Receiving only various error messages. Do you have any idea or an updated tutorial in using SystemJS with Angular 13/14? Thanks in advance!