Creating An Angular Project

In this blog, I am going to demonstrate the process of staring a new Angular project and creating an application.

Preparing a TypeScript Angular Development Environment

You need to have a selected code editor. Here, in my case, I have selected VS 2015. Along with that, I have installed a recent browser, and a recent version of Node.js.

Creating an Angular Project
 
Creating an Angular Project
 
Creating an Angular Project

I have started by creating a project in Visual Studio by selecting File >> New >> Project.

Create a project with a name as you wish. Here, I have selected the name as ProductCart which suits to my project description.

Creating an Angular Project

Select Empty project and MVC as a core reference. As most of us come from .NET MVC background, this makes us more comfortable to see similar things.

Creating an Angular Project

A Two-folder structure is required for an Angular application. The first one contains all the project files and the second folder has all the code.

Now, the recently created project needs some of the folders to be deleted, as highlighted below.

Creating an Angular Project

The structure of our project looks like below

Creating an Angular Project

HTML 5 is required to load the JavaScript files and start the application. Create a default index file.

Index.Html

  1. <!DOCTYPEhtml>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>Test 1</title>  
  6.     <metacharset="utf-8" />  
  7. </head>  
  8.   
  9. <body>  
  10.     <app>Welcome to angular</app>  
  11. </body>  
  12.   
  13. </html> 
An Angular project needs a lot of software packages. Let us install or download them using the Node Package Manager (NPM).To add these packages, I have added the package.json file.

Package.json

  1. {  
  2.     "dependencies": {  
  3.         "@angular/common""2.2.0",  
  4.         "@angular/compiler""2.2.0",  
  5.         "@angular/core""2.2.0",  
  6.         "@angular/platform-browser""2.2.0",  
  7.         "@angular/platform-browser-dynamic""2.2.0",  
  8.         "@angular/upgrade""2.2.0",  
  9.         "@angular/forms""2.2.0",  
  10.         "@angular/http""2.2.0",  
  11.         "reflect-metadata""0.1.8",  
  12.         "rxjs""5.0.0-beta.12",  
  13.         "zone.js""0.6.26",  
  14.         "core-js""2.4.1",  
  15.         "classlist.js""1.1.20150312",  
  16.         "systemjs""0.19.40",  
  17.         "bootstrap""4.0.0-alpha.4"  
  18.     },  
  19.     "decDependencies": {  
  20.         "lite-server""2.2.2",  
  21.         "typescript""2.0.2",  
  22.         "typings""2.1.1",  
  23.         "concurrently""2.2.0"  
  24.     },  
  25.     "scripts": {  
  26.         "start""concurrently \"npm run tswatch\" \"npm run lite \" ",  
  27.         "tsc""tsc",  
  28.         "tswatch""tsc -w",  
  29.         "lite""lite-server",  
  30.         "typings""typings"  
  31.     }  
  32. }  

Now, it's time to install the packages in the project. Open the npm command prompt and go to the project directory and run the npm install command.

Creating an Angular Project
 
Creating an Angular Project
 
Creating an Angular Project

Check the solution. There must be a new folder inside the project node_modules.

Creating an Angular Project

Type definition is the definition used by TypeScript to work on JavaScript libraries. The following website manages the types that I have added to the package.json.

http://definitelytyped.org 

Run the following command in the project folder to download and install the TypeScript files. Hence, these are required by the project.

  • npm run typings - - install dt~core-js - -save - - global
  • npm run typings - - install dt~node - - save - - global

When these commands run, the project will use the scripts section of the package.json file and use the typings package to download the packages.

A folder named Typings will be added to the project and a new option of TypeScript build will appear in the project properties.

Creating an Angular Project

It will add a file called typing.json.

Typing.json

  1. {  
  2.     "globalDependencies": {  
  3.         "core-js""registry:dt/core-js#0.9.0+20170324193834",  
  4.         "node""registry:dt/node#7.0.0+20170322231424"  
  5.     }  

To use the TypeScript complier, we need to create tsconfig.json file as I have created below.

tsconfig.json

  1. {  
  2.     "compilerOptions": {  
  3.         "target""es6",  
  4.         "module""commonjs",  
  5.         "sourceMap"true,  
  6.         "moduleResolution""node",  
  7.         "emitDecoratorMetadata"true,  
  8.         "experimentalDecorators"true,  
  9.         "noStrictGenericChecks"true  
  10.     },  
  11.     "exclude": ["node_modules"]  
  12. }  

Add a file comilertest.ts to the project and test your compiler.

Creating an Angular Project
 
Creating an Angular Project

I have created a model file Product.model.ts.

Product.model.ts

  1. exportclass Product {  
  2.     constructor(public id ? : number, public name ? : string, public category ? : string, public price ? : number) {}  
  3. }  

Now, our model is ready to create a data source for the application. I have created a simple data souce named datasource.model.ts

Datasource.model.ts

  1. import {  
  2.     Product  
  3. } from "./product";  
  4. exportclass SimpleDataSource {  
  5.     private data: Product[];  
  6.     constructor() {  
  7.         this.data = new Array < Product > (new Product(1, "Kayak""Watersports", 275), new Product(2, "Lifejacket""Watersports", 48.95), new Product(3, "Soccer Ball""Soccer", 19.50), new Product(4, "Corner Flag""Soccer", 34.95), new Product(5, "Thinking Cap""Chess", 16));  
  8.     }  
  9.     getData(): Product[] {  
  10.         returnthis.data;  
  11.     }  

Finally, create a repository with Save, Delete, and getproducts methods. I have created it as repository.model.ts

Repository.model.ts

  1. import {  
  2.     Product  
  3. } from "./product";  
  4. import {  
  5.     SimpleDataSource  
  6. } from "./datasource";  
  7. exportclass Model {  
  8.     private datasource: SimpleDataSource;  
  9.     private products: Product[];  
  10.     private locator = (p: Product, id: number) => p.id == id;  
  11.     constructor() {  
  12.         this.datasource = new SimpleDataSource();  
  13.         this.products = new Array < Product > ();  
  14.         this.datasource.getData().forEach(p => this.products.push(p));  
  15.     }  
  16.     getProdcts(): Product[] {  
  17.         returnthis.products;  
  18.     }  
  19.     getProducts(id: number): Product {  
  20.         returnthis.products.find(p => this.locator(p, id));  
  21.     }  
  22.     saveProduct(product: Product) {  
  23.         if (product.id == null || product.id == 0) {  
  24.             product.id = 1;  
  25.             this.products.push(product);  
  26.         } else {  
  27.             let index = this.products.findIndex(p => this.locator(p, p.id));  
  28.             this.products.splice(index, 1, product);  
  29.         }  
  30.     }  
  31.     deleteProduct(id: number) {  
  32.         let index = this.products.findIndex(p => this.locator(p, id));  
  33.         this.products.slice(index, 1);  
  34.     }  
  35.     generateID(): number {  
  36.         let candidate = 100;  
  37.         while (this.getProducts(candidate) != null) {  
  38.             candidate++;  
  39.         }  
  40.         return candidate;  
  41.     }  
  42. }  

Now, let's start creating the template and root component for our productcart.

For now, I will keep my template simple and later at the end, I will modify it to show you Angular in action.

Template.html

  1. <div class=”bg-info p-a-1”> This is my first angular app. </div>  

All the code is written in component, a TypeScript class. The @Component decorator is applied to this class.

Component.ts

  1. import {  
  2.     Component  
  3. } from "@angular/core";  
  4. import {  
  5.     Model  
  6. } from "./repository.model";  
  7. import {  
  8.     Product  
  9. } from "./Product.model";  
  10. @Component({  
  11.     selector: "app",  
  12.     templateUrl: "app/template.html"  
  13. })  
  14. exportclass ProductComponent {  
  15.     model: Model = new Model();  
  16.     getProducts(): Product[] {  
  17.         returnthis.model.getProdcts();  
  18.     }  

App modules is a root module for describing the application. I have added one, i.e., app.module.ts.

App.module.ts

  1. import { NgModule } from"@angular/core";  
  2. import { BrowserModule } from"@angular/platform-browser";  
  3. import { ProductComponent } from"./component";  
  4. @NgModule({  
  5.    declarations: [ProductComponent,],  
  6.    imports: [BrowserModule],  
  7.    bootstrap: [ProductComponent]  
  8. })  
  9. exportclass AppModule { }  

We need to bootstrap the application so as to enable the communication in Angular framework and the application code. For that, I have defined a class below, named as main.ts.

Main.ts

  1. import { platformBrowserDynamic } from"@angular/platform-browser-dynamic";  
  2. import { AppModule } from"./app.module";  
  3. platformBrowserDynamic().bootstrapModule(AppModule);  

Now, we have to create a module loader to load the dependent files.

Systemjs.config.js

  1. (function(global) {  
  2.     var paths = {  
  3.         "rxjs/*""node_modules/rxjs/bundles/Rx.min.js",  
  4.         "@angular/*""node_modules/@angular/*"  
  5.     }  
  6.     var packages = {  
  7.         "app": {}  
  8.     };  
  9.     var angularModules = ["forms""common""compiler""core""platform-browser""platform-browser-dynamic"]  
  10.     angularModules.forEach(function(pkg) {  
  11.         packages["@angular/" + pkg] = {  
  12.             main: "/bundles/" + pkg + ".umd.min.js"  
  13.         };  
  14.     });  
  15.     System.config({  
  16.         paths: paths,  
  17.         packages: packages  
  18.     });  
  19. })(this);  

Finally, here comes the end to include the JS files not loaded in the Module loader.

Index.html

  1. <!DOCTYPEhtml>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>Angular</title>  
  6.     <metacharset="utf-8" />  
  7.     <scriptsrc="node_modules/classlist.js/classList.min.js"> </script> <scriptsrc="node_modules/core-js/client/shim.min.js">  
  8.         </script>  
  9.         <scriptsrc="node_modules/zone.js/dist/zone.min.js"> </script> <scriptsrc="node_modules/reflect-metadata/Reflect.js">  
  10.             </script>  
  11.             <scriptsrc="node_modules/systemjs/dist/system.src.js"> </script> <scriptsrc="systemjs.config.js">  
  12.                 </script>  
  13.                 <script>  
  14.                     System.import("app/main").catch(function(err) {  
  15.                         console.error(err);  
  16.                     });  
  17.                 </script>  
  18.               <linkhref="node_modules/bootstrap/dist/css/bootstrap.min.css"rel="stylesheet"/> </head> <bodyclass="m-a-1">  
  19.              <app>  
  20.         </app>  
  21.    </body>  
  22.   
  23. </html>  

Now, let us build and run the application. Shown below is the result.

Creating an Angular Project

I have added another step for you guys to iterate and display the product cart in template.html.

  1. <tableclass="table table-sm table-bordered m-t-1">  
  2.     <tr>  
  3.         <th>Name</th>  
  4.         <th>Category</th>  
  5.         <th>Price</th>  
  6.     </tr>  
  7.     <tr*ngFor="let item of getProducts()">  
  8.         <td>{{item.name}}</td>  
  9.         <td>{{item.category}}</td>  
  10.         <td>{{item.price}}</td>  
  11.     </tr>  
  12. </table>  

Template.html

  1. <divclass="bg-info p-a-1"> There are {{getProductNumber()}} products. <br />  
  2.     <tableclass="table table-sm table-bordered m-t-1">  
  3.         <tr>  
  4.             <th>Name</th>  
  5.             <th>Category</th>  
  6.             <th>Price</th>  
  7.         </tr>  
  8.         <tr*ngFor="let item of getProducts()">  
  9.             <td>{{item.name}}</td>  
  10.             <td>{{item.category}}</td>  
  11.             <td>{{item.price}}</td>  
  12.          </tr>  
  13.     </table>  
  14. </div>  
Creating an Angular Project