Build Modern App With MEAN Stack 2.0 - Part One

Introduction

 
In the starting phase of JavaScript, it was only limited to the client-side part of the application. We used JavaScript to handle events on the client-side, but in the last few years, everything has changed. Now, JavaScript is not used only for handling the events on the client-side. It has made its way to get used at each phase of software and application development, for example at the 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 the 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 an upper layer of Node, and MongoDB for the database.
 
MEAN Stack
 
So, the 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 formats, like a table, we store data into JSON format.
 

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” stands for AngularJS, a structural framework for dynamic web apps. We use HTML as our template language and use Angular to extend HTML's syntax. The latest version of Angular is 2.0. Angular 2.0 is completely written and now it is component-b component basedack 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 the front-end of the application.
 

Node.js

 
In MEAN stack, “N” stands for the Node.js, Node.js provides an open-source and cross-platform runtime environment for developing server-side applications. Node.js provides a platform to develop an event-driven, non-blocking I/O lightweight and efficient application.
 
The objective of this series is to provide step by step instructions to set up the environment for MEAN Stack 2.0 application and provide 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 an “Employee Management System(EMS)” where we can manage the employee level information like projects undertaken 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 a 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 of 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 recommend you to use the Visual Studio Code; it makes the development easy.

Application Setup

 
Now, let's set up the development environment for our application. First of all, we will create a Server using Node.js and Express and after that, using the Angular2, we will create the front-end of the 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 a Package.json file.
 
In your integrated terminal, paste “npm init” command and press Enter. This command will create the “package.json” file for the 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. 
 
Package.json
 
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”.
 
Package.json
 
Step 2- Add express and other dependencies
 
For the Node.js server setup, we require some packages for Express as an 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, add the “server.js” file in the root directory of the 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 the above three lines, we import the required packages     
  6.     
  7. var index=require('./routes/index');    
  8. var api=require('./routes/api');    
  9.     
  10. // index and API object contains 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 the 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. // Define 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 set up 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 a 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 the 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 the home page, then it will be handled by code written in “index.js” and if the 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 routine, if the 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 the 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 the “client” folder and name this folder as “views”. In the “views” folder, we will create our index.html and Angular2 related code and files. After adding the “client” and “views” folder, now add the “index.html” file in the “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.
 
Mean Stack Application
 
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 server” command. After running this command, if you get the below screen that means everything is configured very well.
 
nodemon sever
 
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.
 
Mean Stack 2 Application
 
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 a database and establish a connection with the 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 the “27017” port and ready to connection with a client.
 
mongod command
 
After starting the server, now we run a client and create a new database. Now, open another command prompt window and run the “mongo” command. This command creates a client and establish the connection to the server running at port “27017”.
 
mongo command
 
After creating the connection to the server, now use "employeeDetails” command, this command creates 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([{  
  2.   "EmployeeName""Ankur Verma",  
  3.   "Designation""Mobile Developer",  
  4.   "Project""OUP",  
  5.   "Skills""Java, Android Studio, Xamarin"  
  6.  }, {  
  7.   "EmployeeName""Dheeraj Sharma",  
  8.   "Designation"" Developer",  
  9.   "Project""Lion Servcies",  
  10.   "Skills""C#,Asp.Net,MVC,AngularJS"  
  11.  },  
  12.  {  
  13.   "EmployeeName""Dhramveer",  
  14.   "Designation"" Developer",  
  15.   "Project""VMesh",  
  16.   "Skills""C#,Asp.Net,MVC,AngularJS"  
  17.  },  
  18.  {  
  19.   "EmployeeName""Prakash",  
  20.   "Designation"" Web Developer",  
  21.   "Project""OUP",  
  22.   "Skills""C#,Asp.Net,MVC,AngularJS"  
  23.  },  
  24.  {  
  25.   "EmployeeName""Raj Kumar",  
  26.   "Designation""Developer",  
  27.   "Project""CNS",  
  28.   "Skills""C#,Asp.Net,MVC"  
  29.  }  
  30. ]) 
insert records in mongodb
 
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.
 
db.employees.find().pretty()
 
Now our database is ready. So, let’s create model classes and make connections to this database.
 
Step 9- Install Mongoose and make a 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 attributes 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 imported the “Employee” model that we created in “dataFile.js” file and executed the “Find” method. The “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 a 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 the 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, the only remaining part is “client” application. Let’s start the working on “client” application of the project.
 
Step 10- Create package.json file
 
Now go to the “client” folder and create a “package.json” file and paste 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.   "type""MIT",  
  12.   "url""https://github.com/angular/angular.io/blob/master/LICENSE"  
  13.  }],  
  14.  "dependencies": {  
  15.   "@angular/common""~2.1.1",  
  16.   "@angular/compiler""~2.1.1",  
  17.   "@angular/core""~2.1.1",  
  18.   "@angular/forms""~2.1.1",  
  19.   "@angular/http""~2.1.1",  
  20.   "@angular/platform-browser""~2.1.1",  
  21.   "@angular/platform-browser-dynamic""~2.1.1",  
  22.   "@angular/router""~3.1.1",  
  23.   "@angular/upgrade""~2.1.1",  
  24.   "angular-in-memory-web-api""~0.1.13",  
  25.   "bootstrap""^3.3.7",  
  26.   "core-js""^2.4.1",  
  27.   "reflect-metadata""^0.1.8",  
  28.   "rxjs""5.0.0-beta.12",  
  29.   "systemjs""0.19.39",  
  30.   "zone.js""^0.6.25"  
  31.  },  
  32.  "devDependencies": {  
  33.   "@types/core-js""^0.9.34",  
  34.   "@types/node""^6.0.45",  
  35.   "angular-cli""^1.0.0-beta.28.3",  
  36.   "concurrently""^3.0.0",  
  37.   "lite-server""^2.2.2",  
  38.   "typescript""^2.0.3"  
  39.  }  
The above code defines all the packages and dependencies that we need to create an Angular2 client and also contains the commands for a 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 the tsconfig.json file
 
Now create another file in client folder. Name 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.  }  
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 the “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.
 
npm install
 
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 {  
  2.  NgModule  
  3. from '@angular/core';  
  4. import {  
  5.  BrowserModule  
  6. from '@angular/platform-browser';  
  7. import {  
  8.  HttpModule  
  9. from '@angular/http';  
  10. import {  
  11.  FormsModule  
  12. from '@angular/forms';  
  13. import {  
  14.  AppComponent  
  15. from './components/app/app.component';  
  16. @NgModule({  
  17.  imports: [BrowserModule, HttpModule, FormsModule],  
  18.  declarations: [AppComponent, ],  
  19.  bootstrap: [AppComponent]  
  20. })  
  21. 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 the 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 {  
  2.  Component  
  3. } from '@angular/core';  
  4. @Component({  
  5.  moduleId: module.id,  
  6.  selector: 'my-app',  
  7.  templateUrl: 'app.component.html'  
  8.   
  9. })  
  10. 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”.
 
integrated Terminal
 
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.
 
MEAN Stack 2
 
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 the 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. <  
  2. base href = "/" / >  
  3.  <  
  4.  link rel = "stylesheet"  
  5. href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >  
  6.   
  7.  <!-- jQuery library -->    
  8.  <  
  9.  script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" > < /script>    
  10.   
  11.  <!-- Latest compiled JavaScript -->    
  12.  <  
  13.  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 the 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 the 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 the following code. 
  1. import {  
  2.  Component  
  3. } from '@angular/core';  
  4.   
  5. @Component({  
  6.  moduleId: module.id,  
  7.  selector: newEmployee,  
  8.  templateUrl: newEmployee.component.html ',    
  9.   
  10. })  
  11. export class newEmployee Component {} 
Let’s add a template file for this component, now create a “newEmployee.component.html” file and paste the 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 the previous step add a “details” folder and add “Details.component.ts” file and paste the following code into this file. 
  1. import {  
  2.  Component  
  3. } from '@angular/core';  
  4.   
  5. @Component({  
  6.  moduleId: module.id,  
  7.  selector: 'details',  
  8.  templateUrl: 'details.component.html',  
  9.   
  10. })  
  11. export class detailsComponent {} 
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 {  
  2.  Component  
  3. } from '@angular/core';  
  4.   
  5. @Component({  
  6.  moduleId: module.id,  
  7.  selector: 'edit',  
  8.  templateUrl: 'edit.component.html',  
  9.   
  10. })  
  11. export class editComponent {} 
Now create the “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 the component section and create a “navmenu.component.ts” file and paste the following code. 
  1. import {  
  2.  Component  
  3. } from '@angular/core';  
  4.   
  5. @Component({  
  6.  moduleId: module.id,  
  7.  selector: 'nav-menu',  
  8.  templateUrl: 'navmenu.component.html',  
  9.  styleUrls: ['navmenu.component.css']  
  10. })  
  11. export class NavMenuComponent {} 
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'  
  5. class = 'navbar-toggle'  
  6. data - toggle = 'collapse'  
  7. data - target = '.navbar-collapse' >  
  8.                 <span class = 'sr-only' > Toggle navigation < /span>  
  9.                 <span class = 'icon-bar' >< /span>  
  10.                 <span class = 'icon-bar' >< /span>  
  11.                 <span class = 'icon-bar' >< /span>  
  12.                 </button>  
  13.                 <a class = 'navbar-brand' [routerLink] = "['/home']" > EMS < /a>  
  14.                 </div><  
  15.  div class = 'clearfix' >< /div>  
  16.  <div class = 'navbar-collapse collapse' >  
  17.      <ul class = 'nav navbar-nav' >  
  18.          <li[routerLinkActive] = "['link-active']" >  
  19.              <a[routerLink] = "['/home']" >  
  20.                  <span class = 'glyphicon glyphicon-home' >< /span> Home   </a>  
  21.                  </li>  
  22.                  <li[routerLinkActive] = "['link-active']" >  
  23.                      <a[routerLink] = "['/new']" >  
  24.                          <span class = 'glyphicon glyphicon-user' >  
  25.                              </span> New Employee     
  26.                              </a>  
  27.                              </li>  
  28.                              </ul>  
  29.                              </div>  
  30.                              </div>  lt;  
  31. </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: 10 px;  
  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: 0 px;  
  39.  }  
  40.  .navbar ul {  
  41.   float: none;  
  42.  }  
  43.  .navbar li {  
  44.   float: none;  
  45.   font - size: 15 px;  
  46.   margin: 6 px;  
  47.  }  
  48.  .navbar li a {  
  49.   padding: 10 px 16 px;  
  50.   border - radius: 4 px;  
  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.  }  
After adding all these components now following will be the structure of our “component” section.
 
MEAN Stack 2
 

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 {  
  2.  NgModule  
  3. } from '@angular/core';  
  4. import {  
  5.  BrowserModule  
  6. } from '@angular/platform-browser';  
  7. import {  
  8.  HttpModule  
  9. } from '@angular/http';  
  10. import {  
  11.  FormsModule  
  12. } from '@angular/forms';  
  13. import {  
  14.  RouterModule  
  15. } from '@angular/router';  
  16. import {  
  17.  AppComponent  
  18. } from './components/app/app.component';  
  19. import {  
  20.  NavMenuComponent  
  21. } from './components/navmenu/navmenu.component';  
  22. import {  
  23.  newEmployeeComponent  
  24. } from "./components/newEmployee/newEmployee.component";  
  25. import {  
  26.  homeComponent  
  27. } from "./components/home/home.component";  
  28. import {  
  29.  editComponent  
  30. } from "./components/edit/edit.component";  
  31. import {  
  32.  detailsComponent  
  33. } from "./components/details/details.component";  
  34. @NgModule({  
  35.  declarations: [  
  36.   AppComponent,  
  37.   NavMenuComponent,  
  38.   newEmployeeComponent,  
  39.   homeComponent,  
  40.   editComponent,  
  41.   detailsComponent  
  42.  ],  
  43.  imports: [BrowserModule,  
  44.   HttpModule,  
  45.   FormsModule,  
  46.   RouterModule.forRoot([{  
  47.     path: '',  
  48.     redirectTo: 'home',  
  49.     pathMatch: 'full'  
  50.    },  
  51.    {  
  52.     path: 'home',  
  53.     component: homeComponent  
  54.    },  
  55.    {  
  56.     path: 'details/:id',  
  57.     component: detailsComponent  
  58.    },  
  59.    {  
  60.     path: 'new',  
  61.     component: newEmployeeComponent  
  62.    },  
  63.    {  
  64.     path: 'edit/:id',  
  65.     component: editComponent  
  66.    },  
  67.    {  
  68.     path: '**',  
  69.     redirectTo: 'home'  
  70.    }  
  71.   ])  
  72.  ],  
  73.  bootstrap: [AppComponent]  
  74. })  
  75. export class AppModule {} 
In the above code lines of code, we register all the components into the “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 the 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.
 
MEAN Stack 2
 
MEAN Stack 2
 
MEAN Stack 2
 
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 requests to the Server.
 
After creating the Service, now we need to register this Service in the 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.
 
 
import service
 
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 subscription. Actually, an Angular 2 provides a new pattern to run asynchronous requests, which are known 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 the 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 the 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.       
  2. <div class="row">  
  3.     <div class="col-md-12">  
  4.         <h3>Employee List</h3>  
  5.         <br />  
  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.                 <tr *ngFor="let empData of EmployeeList  ; let i = index; trackBy: employeeId">  
  33.                     <td>    
  34.                             {{i+1}}    
  35.                         </td>  
  36.                     <td>    
  37.                             {{empData.EmployeeName}}    
  38.                         </td>  
  39.                     <td>    
  40.                            {{empData.Designation}}    
  41.                         </td>  
  42.                     <td>    
  43.                            {{empData.Project}}    
  44.                         </td>  
  45.                     <td>  
  46.                         <a [routerLink]="['/details/',empData._id]"    
  47.                                class="btn btn-primary">    
  48.                                 Detail    
  49.                             </a>  
  50.                         <a [routerLink]="['/edit/',empData._id]"    
  51.                                class="btn btn-success">    
  52.                                 Edit    
  53.                             </a>  
  54.                         <a     
  55.                                class="btn btn-danger" (click)="deleteEmployee(empData._id)">    
  56.                                 Delete    
  57.                             </a>  
  58.                     </td>  
  59.                 </tr>  
  60.             </table>  
  61.         </div>  
  62.     </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.
 
MEAN Stack 2
 

Summary

 
This is the first part of the “Build Modern App with MEAN Stack 2.0” series. Today, we learned how to setup an Angular 2 Application with Node.js. We created a Node.js server, used the mongoose library to make a connection with the 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 Github.