Build Modern App With MEAN Stack 2.0 - Part One

In the starting phase of JavaScript, it was only limited to the client-side part of the application. We used JavaScript to handle events at the the client side, but in the last few years, everything has changed. Now, JavaScript is not used only for handling the events at client side. It has made its way to get used at each phase of a software and application development, for example at database level, server level etc. We can build an application that is completely written on JavaScript technologies from front-end to back-end and also at database level.

MEAN stack applications are just another example of this. MEAN is an acronym for MongoDB, ExpressJS, AngularJS and Node.js. In MEAN stack, we use Angular for front-end, Node for Server, Express as upper layer of Node, and MongoDB for the database.

MEAN Stack

So, MEAN stack application is a combination of 4 JavaScript technologies.

MongoDB

In MEAN stack, “M” represents MongoDB. MOngoDB is an open source NoSQL database that uses a document-oriented data model. In MongoDB, instead of storing data in relational format, like table, we store data into JSON formatted.

ExpressJS

In MEAN stack, “E” stands for ExpressJS. Express.js is a Node.js framework and allows JavaScript to be used outside web browsers for creating web and network applications. This means, we can create the Server and server-side code for an application like most of the other web languages.

AngularJS

In MEAN stack, “A” stand for AngularJS, a structural framework for dynamic web apps. We use HTML as our template language and use Angular to extend HTML's syntax. Latest version of Angular is 2.0 . Angular 2.0 is completely written and now it is component based. In MEAN stack 1.0, we use Angular 1.x version and for MEAN stack 2.0, we use Angular 2.0. In this series, we will use Angular 2.0 for front-end of application.

Node.js

In MEAN stack, “N” stand for the Node.js, Node.js provide open source and cross-platform runtime environment for developing server side application. Node.js provide a platform to develop an event-driven, non-blocking I/O lightweight and efficient application.

Objective of this series is to provide step by step instruction to setup the environment for MEAN Stack 2.0 application and provide a deep knowledge of how MEAN stack application works.

What we will learn from this series

The goal of this series is to start with the basics of MEAN stack development and cover all the concepts that are required for MEAN stack development, and finish with a web application that is completely written in JavaScript technologies. In this series, we will create “Employee Management System(EMS)” where we can manage the employee level information like projectsundertaken by employee and employee’s basic details.

We will cover the following topics in this series.

  • Initial setup with Node.js
  • Add express and make the API
  • Setup database with MongoDB
  • Setup front-end with Angular2
  • Add a new employee entry
  • View list of all employees.
  • Edit the details of an existing employee
  • Delete an existing employee
  • Add filter and search functionality
  • Add Sorting functionality
  • Conclusion

Prerequisites

  • Basic knowledge of Angular2, MongoDB, Node.js and Express.js. If you are fresher to all these terms, then I would prefer you to first take a tour to all these technologies.
  • Pre installation of NPM. If NPM is not configured in your system, then first install NodeJS .
  • Install the Visual Studio Code for IDE. You can use any IDE but I will recommended you to use the Visual Studio Code; it makes the development easy.

Application Setup

Now, let's setup development environment for our application. First of all, we will ceate Server using Node.js and Express and after that, using the Angular2, we will create the front-end of application using MongoDB as our database.

First, create a folder anywhere in your system and name this folder as “MeanStack2”.

Now, open this in Visual Studio Code.
 
Go to “View” tab and click on “Integrated Terminal”.
 
After opening the Integrated Terminal, now follow the below steps to the application. 

Step 1 Create Package.json file.

In your integrated terminal, paste “npm init” command and press Enter. This command will create the “package.json” file for Node.js application. When you run this command, it will ask you to enter some information like name, version, license etc. The point to consider is that it will ask you about the “entry point” of application. For “entry point”, write the “server.js” instead of “index.js”. For other fields, you can enter any information that you want.

MEAN Stack

After completing this step, you can see that a “package.json” file has been created and this file contains the information that we enter in “Integrated Terminal”.

JSON

Step 2 Add express and other dependencies

For Node.js server setup, we require some packages for Express as upper layer of Node.js, EJS is a template engine and body-parser to parse the request body. So, paste “npm install express body-parser ejs –save” command in your integrated terminal and press Enter. This command adds three packages in “node_modules” folder and also adds the dependency in your “package.json” file.

JSON

Step 3 Add “server.js” file

As we defined in our “package.json” file that “server.js” file is the entry point of our application, so add the “server.js” file in root directory of application and paste the following code into this file.

  1. var express=require('express');  
  2. var path=require('path');  
  3. var bodyParser=require('body-parser');  
  4.   
  5. // In above three line we import the required packages   
  6.   
  7. var index=require('./routes/index');  
  8. var api=require('./routes/api');  
  9.   
  10. // index and api object contain the path of routing files for our application  
  11.   
  12. var port=4500;  
  13. var app=express();  
  14.   
  15. //Define the port and create an object of express class  
  16.   
  17. app.set('view engine','ejs');  
  18. app.set('views',path.join(__dirname,'/client/views'));  
  19.   
  20. // define the view engine and set the path for views files  
  21.   
  22. app.engine('html',require('ejs').renderFile);  
  23. //Register given template engine callbac function as extension  
  24.   
  25. app.use(express.static(path.join(__dirname,'/client')));  
  26.   
  27. // Defien the path for the static files like image, css and js files  
  28.   
  29. app.use(bodyParser.json());  
  30. app.use(bodyParser.urlencoded({extended:false}));  
  31. // Define the middleware to parse the data from URL request and requesy body  
  32.   
  33. app.use('/',index);  
  34. app.use('/api',api);  
  35. app.use('*',index);  
  36. // define the middleware for routing  
  37.   
  38. app.listen(port,function(){  
  39.     console.log('Server Started At '+port);  
  40. })  
  41. // Run the Node.js server at 4500 port   

In the above lines of code, we created a Server and set all the middleware and other required dependencies. Later, we run this server on “4500” port. In the first three lines of code, we imported the required modules to setup the Server. In the next line, we imported “index” and “api” files. Actually in these two files, we implement the routing for our application. Later, we set the “ejs” as template view engine for our application and set the path of our template pages. Using the “express.static” middle-ware function, we define the path for the static files images, JS, and CSS files. 

  1. app.use(bodyParser.json());  
  2. app.use(bodyParser.urlencoded({extended:false}));   

In these two lines of code we set the bodyParser and urlencoded middle-ware. The “bodyParser” middle-ware is used to get the data from request body like POST, PUT and DELETE type request. The “urlEncoded” middle-ware is used to get the data from URL of the request. 

  1. app.use('/',index);  
  2. app.use('/api',api);  
  3. app.use('*',index);   

In the above lines of code, we set the middleware for the “/” and “api” and requests. It means if the request is for home page, then it will be handled by code written in “index.js” and if request is related to the “api”, then it will be handled by code written in “api.js’ file. We have also defined the default routing; in case of default, it will be handled by the “index.js” file. 

  1. app.listen(port,function(){   
  2.     console.log('Server Started At '+port);  
  3. })   

In the above line of code, we set the server which will listen to the “4500” port number.

Step 4 Add routing files

Now, add the “route” folder to the root directory of the of application. After creating the “route” folder, now add “index.js” file and paste the following code into this file. 

  1. var express=require('express');  
  2. var router=express.Router();  
  3.   
  4. router.get('/',function(req,resp,next){  
  5.     resp.render('index.html');  
  6. });  
  7.   
  8. module.exports=router;   

In the above lines of code, we performed the routing, if request is get type, then we will render the user to “index.html” page that is present in “client/views” folder. After creating the “index.js” page, now add another page and named this page as “api.js”, and paste the following code into this file. 

  1. var express=require('express');  
  2. var router=express.Router();  
  3.   
  4. router.get('/',function(req,resp,next){  
  5.     resp.send('this is api data');  
  6. });  
  7.   
  8. module.exports=router;   

In the above code, we are sending a simple text message response to the request. 

Step 5 Add Client folder

Now, add a “client” folder in your application root. This folder will contain all the client side related code. After creating this file, now add another folder in “client” folder and name this folder as “views”. In “views” folder, we will create our index.html and Angular2 related code and files. After adding the “client” and “views” folder, now add “index.html” file in “views” folder and paste the following code into this file. 

  1. <html>  
  2.     <head>  
  3.     </head>  
  4.     <body>  
  5.         <h2>This is Mean Stack2 Application.</h2>  
  6.     </body>  
  7. </html>   

So far, we have performed all the basic required configuration to run the server and check the client application. Let’s check the structure of our application. Following will be the structure of our application.

JSON

Step 6 Install the Nodemon

We can run any node.js file using the “node” command but if we make any changes in our files, then we need to restart our server again and again; that takes a lot of time. To overcome this scenario, we can add the “nodemon”. Nodemon will watch the files in the directory in which it was started, and if any files are made changes in, nodemon will automatically restart your node application. To add the “nodemon” package, open your command line terminal and paste the "npm install –g nodemon” line of code and press Enter.

Step 7 Run the application

After adding the “nodemon”, now go to “Integrated Terminal” of Visual Studio Code and run the “nodemon sever” command. After running this command, if you get below screen that means everything is configured very well.

JSON
Now, open your browser and paste the “localhost:4500” URL and hit enter. When press the enter and everything is configured properly then you will get this screen.

JSON
If you are not getting this screen that means something is going wrong with your code and try to find and resolve that issue. Now we create a database and establish the a connection with this database using the “mongoose” library.

Step 8 Create database and establish the connection with database

If you have installed the “MongoDB” then open a command prompt window and run the “mongod” command, this command run the “MongoDB” server at “27017” port and ready to connection with a client.

JSON

After starting the sever now we run a client and create a new database. Now open another command prompt window and run the “mongo” command, this command create a client and establish the connection to server running at port “27017”.

JSON

 After creating the connection to server now “use employeeDetails” command, this command create a new database (employeeDetails) and switched to this new database.

 Now paste the following code into client command prompt and press enter. 

  1. db.employees.insert([{"EmployeeName":"Ankur Verma","Designation":"Mobile Developer","Project":"OUP","Skills":"Java, Android Studio, Xamarin"},{"EmployeeName":"Dheeraj Sharma","Designation":" Developer","Project":"Lion Servcies","Skills":"C#,Asp.Net,MVC,AngularJS"},  
  2. {"EmployeeName":"Dhramveer","Designation":" Developer","Project":"VMesh","Skills":"C#,Asp.Net,MVC,AngularJS"},  
  3. {"EmployeeName":"Prakash","Designation":" Web Developer","Project":"OUP","Skills":"C#,Asp.Net,MVC,AngularJS"},  
  4. {"EmployeeName":"Raj Kumar","Designation":"Developer","Project":"CNS","Skills":"C#,Asp.Net,MVC"}])   

JSON

The above code creates a new collection in our database and inserts some data into this collection. After inserting some default data into “employees” collection’ let’s check the data that we entered. To get the data from a collection we run the “find” command.

Now paste “db.employees.find().pretty()” command and press the enter. When you run this command it will show all the data of “employees” collection.

JSON

Now our database is ready let’s create model classes and make a connections to this database.

Step 9 Install Mongoose and make connection to the database.

Now open “Integrated Terminal” of Visual Studio Code and run the “npm install mongoose --save” command, this command will install the dependencies for the mongoose. In this project we are going to use the “mongoose” for MongoDB CRUD operation. The mongoose is an object modeling package for Node that essentially works like an ORM that you would see in other languages (Entity framework for C#). Using Mongoose, we can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB.

After installing the dependency for mongoose now create a “database” folder in root directory of the project and create a “dataFile.js” file in this folder and paste the following code into this file. 

  1. var mongoose = require('mongoose');   
  2. // Connection URL    
  3. var db = 'mongodb://localhost:27017/employeeDetails';    
  4.     // Use connect method to connect to the Server    
  5.  mongoose.connect(db, function (error) {  
  6.     if (error) {  
  7.         console.log(error);  
  8.     }  
  9. });  
  10.   
  11. var Schema = mongoose.Schema;  
  12. var Employee_Schema = new Schema({  
  13.     EmployeeName: String,  
  14.     Designation: String,  
  15.     Project: String,  
  16.     Skills:String  
  17. });  
  18.   
  19. var Employee = mongoose.model('employees', Employee_Schema);  
  20.    
  21.  module.exports=Employee;   

In first lines of code we simply make a connection to our MongoDB database. We create a schema for the “employees” collection and defines in total four attribute for the “Employee_Schema” and in the next line we create an “employees” model using this schema. So when we perform any CRUD operation we will take this employee model and perform the CRUD operations. 

After creating the Employee models and schema now go to “api.js” file and replace the code of this file with following code. 

  1. var express=require('express');  
  2. var router=express.Router();  
  3.   
  4. var Employee=require('../database/dataFile');  
  5.   
  6. router.get('/',function(req,resp,next){  
  7.     Employee.find({},function(err,docs){  
  8.         resp.send(docs);  
  9.     })  
  10. });  
  11.   
  12.  module.exports=router;   

In the above code we import the “Employee” model that we created in “dataFile.js” file and execute the “Find” method, this “find” method is similar to the “find” method of the MongoDB, so when we hit this api it will fetch out the all record form “Employees” collection and return this data as response. Let’s check if it is working or not. Now save all the changes and open you browser and paste this URL “http://localhost:4500/api” in browser and press the enter. When we hit the “api/” route it will return the list of all employees as below.

JSON

Now our “API”, “Database” and “Server” all are ready, only remaining part is “client” application. Let’s start the work on “client” application of the project.

Step 10 Create package.json file

Now go to “client” folder and create a “package.json” file and past the below code into this file. 

  1. {  
  2.   "name""mytasklist",  
  3.   "version""1.0.0",  
  4.   "scripts": {  
  5.     "start""concurrently \"npm run tsc:w\" \"npm run lite\" ",  
  6.     "lite""lite-server",  
  7.     "tsc""tsc",  
  8.     "tsc:w""tsc -w"  
  9.   },  
  10.   "licenses": [  
  11.     {  
  12.       "type""MIT",  
  13.       "url""https://github.com/angular/angular.io/blob/master/LICENSE"  
  14.     }  
  15.   ],  
  16.   "dependencies": {  
  17.     "@angular/common""~2.1.1",  
  18.     "@angular/compiler""~2.1.1",  
  19.     "@angular/core""~2.1.1",  
  20.     "@angular/forms""~2.1.1",  
  21.     "@angular/http""~2.1.1",  
  22.     "@angular/platform-browser""~2.1.1",  
  23.     "@angular/platform-browser-dynamic""~2.1.1",  
  24.     "@angular/router""~3.1.1",  
  25.     "@angular/upgrade""~2.1.1",  
  26.     "angular-in-memory-web-api""~0.1.13",  
  27.     "bootstrap""^3.3.7",  
  28.     "core-js""^2.4.1",  
  29.     "reflect-metadata""^0.1.8",  
  30.     "rxjs""5.0.0-beta.12",  
  31.     "systemjs""0.19.39",  
  32.     "zone.js""^0.6.25"  
  33.   },  
  34.   "devDependencies": {  
  35.     "@types/core-js""^0.9.34",  
  36.     "@types/node""^6.0.45",  
  37.     "angular-cli""^1.0.0-beta.28.3",  
  38.     "concurrently""^3.0.0",  
  39.     "lite-server""^2.2.2",  
  40.     "typescript""^2.0.3"  
  41.   }  
  42. }   

The above code defines all the packages and dependencies that we need to create a Angular2 client and also contains the commands for start, typescript, and lite server. Lite-server provides a Lightweight development only node server that serves a web app, opens it in the browser, refreshes when html or javascript change, injects CSS changes using sockets, and has a fallback page when a route is not found.

Step 11 Create tsconfig.json file

Now create another file in client folder and named this file as “tsconfig.json” and paste the following code into this file. This file contains the some configuration code for the typescript. 

  1. {  
  2.   "compilerOptions": {  
  3.     "target""es5",  
  4.     "module""commonjs",  
  5.     "moduleResolution""node",  
  6.     "sourceMap"true,  
  7.     "emitDecoratorMetadata"true,  
  8.     "experimentalDecorators"true,  
  9.     "removeComments"false,  
  10.     "noImplicitAny"false  
  11.   }  
  12. }   

 Step 12 Create systemjs.config.js file

Again create a new file in client folder and named this file as “systems.config.js” and paste the following code into this file. This file contains all information about the client system like angular packages, path and main file for the application(main.js) and also contains other information. 

  1. /** 
  2.  * System configuration for Angular samples 
  3.  * Adjust as necessary for your application needs. 
  4.  */  
  5. (function (global) {  
  6.   System.config({  
  7.     paths: {  
  8.       // paths serve as alias  
  9.       'npm:''node_modules/'  
  10.     },  
  11.     // map tells the System loader where to look for things  
  12.     map: {  
  13.       // our app is within the app folder  
  14.       app: 'app',  
  15.       // angular bundles  
  16.       '@angular/core''npm:@angular/core/bundles/core.umd.js',  
  17.       '@angular/common''npm:@angular/common/bundles/common.umd.js',  
  18.       '@angular/compiler''npm:@angular/compiler/bundles/compiler.umd.js',  
  19.       '@angular/platform-browser''npm:@angular/platform-browser/bundles/platform-browser.umd.js',  
  20.       '@angular/platform-browser-dynamic''npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',  
  21.       '@angular/http''npm:@angular/http/bundles/http.umd.js',  
  22.       '@angular/router''npm:@angular/router/bundles/router.umd.js',  
  23.       '@angular/forms''npm:@angular/forms/bundles/forms.umd.js',  
  24.       // other libraries  
  25.       'rxjs':                      'npm:rxjs',  
  26.       'angular-in-memory-web-api''npm:angular-in-memory-web-api',  
  27.     },  
  28.     // packages tells the System loader how to load when no filename and/or no extension  
  29.     packages: {  
  30.       app: {  
  31.         main: './main.js',  
  32.         defaultExtension: 'js'  
  33.       },  
  34.       rxjs: {  
  35.         defaultExtension: 'js'  
  36.       },  
  37.       'angular-in-memory-web-api': {  
  38.         main: './index.js',  
  39.         defaultExtension: 'js'  
  40.       }  
  41.     }  
  42.   });  
  43. })(this);   

Step 13 Install all the packages

We defined a list of the packages in “package.json” file, so now we install all these packages. For this move to your “client” directory and run the “npm install --save” command this command take a little bit time and install all the packages that we defined in “package.json” file. After completion of this command you will find that a new folder “node_modules” has been created and this folder contains all the required modules.

JSON

Step 14 Create app.module.ts file

Now, create a folder in your client directory and named this folder as “app”. After creating the folder now create “app.module.ts” file and paste the following code into this file. The app.module.ts file is parent module of all other modules, when ever we create a component, services, filter and directives then first of all we need to register all of these in app.module.ts file. 

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { HttpModule } from '@angular/http';  
  4. import { FormsModule } from '@angular/forms';  
  5. import { AppComponent } from './components/app/app.component';  
  6. @NgModule({  
  7.     imports: [BrowserModule, HttpModule, FormsModule],  
  8.     declarations: [AppComponent,  
  9.     ],  
  10.     bootstrap: [AppComponent]  
  11. })  
  12. export class AppModule { }   

Step 15 Create Main.ts file

Now create a new file in client directory and name this file as “main.ts” and paste the following code into this file. This file is the starting point of our application and bootstrap the AppModule.  

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

Step 16 Create app component

Now create an “app” folder in client directory. In this app folder we will insert all our components, services and custom filters. After creating the “app” folder now create another folder in this “App” folder and name this folder “components;” in this “component” folder we will create the components. After creating the “components” again create an “app” folder into this “components” folder, in this “app” folder we create files for the “app” component.

Now create an “app.component.ts” file and paste the following code into this file. 

  1. import { Component } from '@angular/core';  
  2. @Component({  
  3.   moduleId: module.id,  
  4.   selector: 'my-app',  
  5.   templateUrl: 'app.component.html'  
  6.   
  7. })  
  8. export class AppComponent { }   

In the above code we create a simple component and defined the app.component.html” as templateUrl for this component, so we need to create an html template file also. Again create a file and name this file as “app.component.html” and paste the following code into this file. 

  1. <div class="container">  
  2.     <h1>Congrats! You set MEAN Stack2 Application Successfully</h1>  
  3. </div>   

So far we have created all the files and made all the setup that is required to run a MEAN Stack application, a last step is running the application that starts the client app. Now open “integrated Terminal”, move to “client” directory and run the “npm start” command. This command builds all the typescript files and creates the corresponding JavaScript and map files. The “npm start” command run the “lite server”.

JSON

If your “node” server is already running then refresh the browser else run the “nodemon server” command and you will get the following output on your screen.

JSON
If you get the above screen then congratulations to you, here we complete the MEAN Stack configuration and now we start the work on our “Employee Management” system part. If you don’t get above screen then there is a chance that you are getting some error, so try to resolve that error.

Add bootstrap and create project layout:

So far we successfully configured the MEAN Stack 2 application, now we add some required files for the bootstrap and create the layout for our application. Now go to “index.html” file add the following code at top of the head section. In below code we add CDN for the jQuery and bootstrap and we also add a “base” tag in the first line, this base tag will be used at the time of routing and provide a base(common) URL to all the routes that we will create later in this project. 

  1. <base href="/" />  
  2.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  3.   
  4. <!-- jQuery library -->  
  5. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>  
  6.   
  7. <!-- Latest compiled JavaScript -->  
  8. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>   

Create Home component

We create a home component and show the list of all employees using this component. Now go to component folder add a new folder and name this folder as “home”, in this folder now add a new “home.component.ts” file and paste following code. 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'home',  
  6.     templateUrl: 'home.component.html',  
  7.       
  8. })  
  9. export class homeComponent {  
  10. }   

Now, create a “home.component.html” file and paste following code into this file.

  1. <h1>This is home page</h1>   

Add newEmployee component

Using this component we will provide the functionality to add a new employee. Now go to component folder add a new folder and name this folder as “newEmployee”, in this folder now add a new “newEmployee.component.ts” file and paste following code. 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: newEmployee,  
  6.     templateUrl: newEmployee.component.html',  
  7.       
  8. })  
  9. export class newEmployee Component {  
  10. }   

Let’s add a template file for this component, now create a “newEmployee.component.html” file and paste following code into this file.

  1. <h2>Add New Employee</h2>   

Add details Component

Using the “details” component we will show the details of an employee. Similar to previous step add a “details” folder and add “Details.component.ts” file and paste the following code into this file. 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'details',  
  6.     templateUrl: 'details.component.html',  
  7.       
  8. })  
  9. export class detailsComponent {  
  10. }   

Now create a “details.component.html” page and paste the following code into this file.

  1. <h2>This is a Details page</h2>   

Add edit component

Using this component we add the functionality to edit the information of an existing employee. So create an “edit” folder and create “Edit.component.ts”file and paste following code into this file. 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'edit',  
  6.     templateUrl: 'edit.component.html',  
  7.       
  8. })  
  9. export class editComponent {  
  10. }   

Now create “edit.component.html” page and paste the following code.

  1. <h1>This is edit page</h1>   

Create navMenu Component

We will add a side menu into our application and using this side menu we will provide the functionality of redirecting to the “newEmployee” and “Home” page of the application. So add a “navmenu” folder into component section and create a “navmenu.component.ts” file and paste the following code. 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'nav-menu',  
  6.     templateUrl: 'navmenu.component.html',  
  7.     styleUrls: ['navmenu.component.css']  
  8. })  
  9. export class NavMenuComponent {  
  10.  

Now create a “navmenu.component.html” file and paste the following code. 

  1. <div class='main-nav'>  
  2.    <div class='navbar navbar-inverse'>  
  3.        <div class='navbar-header'>  
  4.            <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>  
  5.                <span class='sr-only'>Toggle navigation</span>  
  6.                <span class='icon-bar'></span>  
  7.                <span class='icon-bar'></span>  
  8.                <span class='icon-bar'></span>  
  9.            </button>  
  10.            <a class='navbar-brand' [routerLink]="['/home']">EMS</a>  
  11.        </div>  
  12.        <div class='clearfix'></div>  
  13.        <div class='navbar-collapse collapse'>  
  14.            <ul class='nav navbar-nav'>  
  15.                <li [routerLinkActive]="['link-active']">  
  16.                    <a [routerLink]="['/home']">  
  17.                        <span class='glyphicon glyphicon-home'></span> Home  
  18.                    </a>  
  19.                </li>  
  20.                <li [routerLinkActive]="['link-active']">  
  21.                    <a [routerLink]="['/new']">  
  22.                        <span class='glyphicon glyphicon-user'></span> New Employee  
  23.                    </a>  
  24.                </li>  
  25.            </ul>  
  26.        </div>  
  27.    </div>  
  28. lt;/div>   

After creating the “.ts” and “.html” file now we create a “.css” file to add the style for this sidemenu, so add the “sidemenu.component.css” file and paste the following code into this file. 

  1. li .glyphicon {  
  2.     margin-right: 10px;  
  3. }  
  4.   
  5. /* Highlighting rules for nav menu items */  
  6. li.link-active a,  
  7. li.link-active a:hover,  
  8. li.link-active a:focus {  
  9.     background-color: #4189C7;  
  10.     color: white;  
  11. }  
  12.   
  13. /* Keep the nav menu independent of scrolling and on top of other items */  
  14. .main-nav {  
  15.     position: fixed;  
  16.     top: 0;  
  17.     left: 0;  
  18.     right: 0;  
  19.     z-index: 1;  
  20. }  
  21.   
  22. @media (min-width: 768px) {  
  23.     /* On small screens, convert the nav menu to a vertical sidebar */  
  24.     .main-nav {  
  25.         height: 100%;  
  26.         width: calc(25% - 20px);  
  27.     }  
  28.     .navbar {  
  29.         border-radius: 0px;  
  30.         border-width: 0px;  
  31.         height: 100%;  
  32.     }  
  33.     .navbar-header {  
  34.         float: none;  
  35.     }  
  36.     .navbar-collapse {  
  37.         border-top: 1px solid #444;  
  38.         padding: 0px;  
  39.     }  
  40.     .navbar ul {  
  41.         float: none;  
  42.     }  
  43.     .navbar li {  
  44.         float: none;  
  45.         font-size: 15px;  
  46.         margin: 6px;  
  47.     }  
  48.     .navbar li a {  
  49.         padding: 10px 16px;  
  50.         border-radius: 4px;  
  51.     }  
  52.     .navbar a {  
  53.         /* If a menu item's text is too long, truncate it */  
  54.         width: 100%;  
  55.         white-space: nowrap;  
  56.         overflow: hidden;  
  57.         text-overflow: ellipsis;  
  58.     }  
  59. }   

After adding all these components now following will be the structure of our “component” section.

JSON

Register the components and perform the routing

After creating all the required components now we need to register all these components into “app.modules.ts” file, so open your “app.modules.ts” file and replace the code with following code into this file. 

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { HttpModule } from '@angular/http';  
  4. import { FormsModule } from '@angular/forms';  
  5. import { RouterModule } from '@angular/router';  
  6. import { AppComponent } from './components/app/app.component';  
  7. import {NavMenuComponent}  from './components/navmenu/navmenu.component';  
  8. import { newEmployeeComponent } from "./components/newEmployee/newEmployee.component";  
  9. import {homeComponent}  from "./components/home/home.component";  
  10. import {editComponent} from "./components/edit/edit.component";  
  11. import {detailsComponent} from "./components/details/details.component";  
  12. @NgModule({  
  13.     declarations: [  
  14.     AppComponent,  
  15.     NavMenuComponent,  
  16.     newEmployeeComponent,  
  17.     homeComponent,  
  18.     editComponent,  
  19.     detailsComponent  
  20.     ],  
  21.     imports: [BrowserModule,  
  22.      HttpModule,  
  23.     FormsModule,  
  24.     RouterModule.forRoot([  
  25.             { path: '', redirectTo: 'home', pathMatch: 'full' },  
  26.             { path: 'home', component: homeComponent },  
  27.             { path: 'details/:id', component: detailsComponent },  
  28.             { path: 'new', component: newEmployeeComponent },  
  29.             { path: 'edit/:id', component: editComponent },  
  30.             { path: '**', redirectTo: 'home' }  
  31.         ])],  
  32.     bootstrap: [AppComponent]  
  33. })  
  34. export class AppModule { }   

In the above code lines of code we register all the components into “declarations” section and also perform the routing for these components.

Add router-outlet

Now go to your “app.component.html” page and replace the code of this file with following code. 

  1. <div class='container-fluid'>  
  2.     <div class='row'>  
  3.         <div class='col-sm-3'>  
  4.             <nav-menu></nav-menu>  
  5.         </div>  
  6.         <div class='col-sm-9 body-content'>  
  7.            <router-outlet></router-outlet>  
  8.         </div>  
  9.     </div>  
  10. </div>   

In above code we add the “sidemenu” using the “nav-menu” selector and also add the “router-outlet”, this router-outlet works as a primary outlet for all the components, in other words RouterOutlet is a “placeholder” component that gets expanded to each route's content.

After making all the changes now save all the changes and refresh or restart your application. Now the following will be the structure of our application.

JSON

JSON

JSON

Add service

Now, our API is ready to return the employee list. Let’s use this API and display the employee information. We need a Service, which can use this API and get the result. Add a Service folder in an app section. After creating the folder, add a TypeScript file and name this file as services.ts and paste the code given below into this file.  

  1. import { Injectable } from '@angular/core';  
  2. import { Http, Headers, RequestOptions, Response } from '@angular/http';  
  3. import { Observable } from "RxJS/Rx";  
  4.   
  5. @Injectable()  
  6. export class EmployeeServcies {  
  7.     constructor(private http: Http) {  
  8.          
  9.     }  
  10.     getEmployeeList() {  
  11.         return this.http.get('http://localhost:4500/api');  
  12.     }  
  13.       
  14. }   

In the code given above, we create an EmployeeServcies class and decorate this with @Injectable meta data. “@Injectbale meta data is used to define a class as a Service. In this Service class, we add getEmployeeList method. In this method, we are using GET method of HTTP class to perform HTTP GET request to the Server.

After creating the Service, now we need to register this Service in app.modules.ts file. Open your app.modules.ts file, import this Service and register this Service into providers. We are registering this Service in an app.modules.ts file, which means now this Service is a global Service. We can use this Service in any component and we don’t need to register this Service in each component.

JSON

After creating and registering the Service, now we use this Service in our home component, so open home.component.ts file and paste the code given below.  

  1. import { EmployeeServcies } from './../../services/services';  
  2. import { Component } from '@angular/core';  
  3. import { Response } from '@angular/http';  
  4.   
  5. @Component({  
  6.     moduleId: module.id,  
  7.     selector: 'home',  
  8.     templateUrl: 'home.component.html',  
  9.       
  10. })  
  11. export class homeComponent {  
  12.       public EmployeeList = [];  
  13.     public constructor(private empService: EmployeeServcies) {  
  14.         this.empService.getEmployeeList()  
  15.             .subscribe(  
  16.             (data: Response) => (this.EmployeeList = data.json())  
  17.             );  
  18.   
  19.     }  
  20. }   

In the code given above, we create an instance(empService) of EmployeeServcies Service and use the getEmployeeList method of this Service to get the employee list. You can see that we are using a subscribe. Actually, an Angular 2 provides a new pattern to run asynchronous requests, which are knojwn as Observables, http is the successor to Angular 1's $http. Instead of returning a Promise, its http.get() method returns an Observable object. Using subscribe method we can use the observable, the “subscribe” method tells the observable that you perform your task here is some one who listening and watching you. Perform the callback function when you return the result. In subscribe method, we get the data and assign the data into EmployeeList. Now, we use this list to display the employee list.

 Open home.component.html file and paste the code given below.  

  1. <div class="row">  
  2.     <div class="col-md-12">  
  3.         <h3>Employee List</h3>  
  4.         <br />  
  5.          
  6.     </div>  
  7. </div>  
  8. <div class="row">  
  9.     <div class="table-responsive">  
  10.         <table class="table">  
  11.             <thead>  
  12.                 <tr>  
  13.                     <th>  
  14.                           
  15.                         S.No.  
  16.                     </th>  
  17.                     <th>  
  18.                         EmployeeName  
  19.                     </th>  
  20.                     <th>  
  21.                         Designation  
  22.                     </th>  
  23.                     <th>  
  24.                         Project  
  25.                     </th>  
  26.                     <th>  
  27.                         Action  
  28.                     </th>  
  29.                 </tr>  
  30.             </thead>  
  31.             <tbody>  
  32.                   
  33.                 <tr *ngFor="let empData of EmployeeList  ; let i = index; trackBy: employeeId">  
  34.                     <td>  
  35.                         {{i+1}}  
  36.                     </td>  
  37.                     <td>  
  38.                         {{empData.EmployeeName}}  
  39.                     </td>  
  40.                     <td>  
  41.                        {{empData.Designation}}  
  42.                     </td>  
  43.                     <td>  
  44.                        {{empData.Project}}  
  45.                     </td>  
  46.                     <td>  
  47.   
  48.                         <a [routerLink]="['/details/',empData._id]"  
  49.                            class="btn btn-primary">  
  50.                             Detail  
  51.                         </a>  
  52.                         <a [routerLink]="['/edit/',empData._id]"  
  53.                            class="btn btn-success">  
  54.                             Edit  
  55.                         </a>  
  56.                         <a   
  57.                            class="btn btn-danger" (click)="deleteEmployee(empData._id)">  
  58.                             Delete  
  59.                         </a>  
  60.                     </td>  
  61.                 </tr>  
  62.                   
  63.         </table>  
  64.     </div>  
  65. </div>     

In the code given above, we perform ngFor on an EmployeeList and create a list of employees. We also add three anchor tags (Edit, Delete and Detail) for an each employee entry. We use the routerLink to link the anchor tag to the specific part of our app.

After making all the changes, save the project and refresh the browser and you will get the result given below.

JSON

Summary

This is the first part of “Build Modern App with MEAN Stack 2.0” series. Today, we learned how to setup Angular 2 Application with Node.js. We created a Node.js server, used the mongoose library to make the connection with MongoDB database. We created some components, and performed the routing for these components. We created Service to get the data from Web API, using builtin http Service, and displayed this data in a tabular format. In the next article, we will create some screens to add, delete or edit the employee information. We also provide the functionality of searching and sorting employee information.

You can download this project from the Github.