In this article, we’ll learn to create basic CRUD application using Angular 5, Nodejs, Express and MongoDB NoSQL database.

Introduction

We will create a demo project using Angular CLI for front-end, Node.js and Express for middle-end, and MongoDB for the back-end. In this article, we start from the beginning.

Requirement

If you already installed Angular CLI, globally check the version with this command ng -v

Download links

Let’s start and create demo application.

Step 1

Create a new folder with any name, let's say, AngularCRUD. After the folder is created, then press ctrl+shift Right click for opening the command window here.

Step 2

After the folder opens in the command prompt, run this command for Angular CLI to install in our folder.

npm install -g @angular/cli

Step 3

If installed successfully, then run this command for creating a new application. Let's again set the project name as AngularCRUD.

ng new projectname

Step 4

When the ng new command is created and installed successfully, change your directory

cd AngularCRUD.

Step 5

Now, we open our project in Visual Studio code with code command like this.



Now, we can see VSCode opened automatically.



Step 6

Now run your application by using this command -
ng serve - o
Here, -o stands for opening application in default browser.


Step 7

Now, let us install Express and Mongoose body parser using this command.
  • npm install express --save
  • npm install mongoose -- save
  • npm install body-parser --save

Step 8

After installing the above three packages, create a new file, server.js.

  1. var express = require('express');
  2. var path = require("path");
  3. var bodyParser = require('body-parser');
  4. var mongo = require("mongoose");
  5. var db = mongo.connect("mongodb://localhost:27017/AngularCRUD", function(err, response){
  6. if(err){ console.log( err); }
  7. else{ console.log('Connected to ' + db, ' + ', response); }
  8. });
  9. var app = express()
  10. app.use(bodyParser());
  11. app.use(bodyParser.json({limit:'5mb'}));
  12. app.use(bodyParser.urlencoded({extended:true}));
  13. app.use(function (req, res, next) {
  14. res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
  15. res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  16. res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  17. res.setHeader('Access-Control-Allow-Credentials', true);
  18. next();
  19. });
  20. var Schema = mongo.Schema;
  21. var UsersSchema = new Schema({
  22. name: { type: String },
  23. address: { type: String },
  24. },{ versionKey: false });
  25. var model = mongo.model('users', UsersSchema, 'users');
  26. app.post("/api/SaveUser",function(req,res){
  27. var mod = new model(req.body);
  28. if(req.body.mode =="Save")
  29. {
  30. mod.save(function(err,data){
  31. if(err){
  32. res.send(err);
  33. }
  34. else{
  35. res.send({data:"Record has been Inserted..!!"});
  36. }
  37. });
  38. }
  39. else
  40. {
  41. model.findByIdAndUpdate(req.body.id, { name: req.body.name, address: req.body.address},
  42. function(err,data) {
  43. if (err) {
  44. res.send(err);
  45. }
  46. else{
  47. res.send({data:"Record has been Updated..!!"});
  48. }
  49. });
  50. }
  51. })
  52. app.post("/api/deleteUser",function(req,res){
  53. model.remove({ _id: req.body.id }, function(err) {
  54. if(err){
  55. res.send(err);
  56. }
  57. else{
  58. res.send({data:"Record has been Deleted..!!"});
  59. }
  60. });
  61. })
  62. app.get("/api/getUser",function(req,res){
  63. model.find({},function(err,data){
  64. if(err){
  65. res.send(err);
  66. }
  67. else{
  68. res.send(data);
  69. }
  70. });
  71. })
  72. app.listen(8080, function () {
  73. console.log('Example app listening on port 8080!')
  74. })

Step 9

Let us open the project folder in other command prompt and run the node server.js on port 8080.

Setp 10

Create a new Angular Service for common AJAX API calling. Use thie commond

ng g s common –spec=false


Step 11

Write the following code in common.service.ts for API.
  1. import { Injectable } from '@angular/core';
  2. import {Http,Response, Headers, RequestOptions } from '@angular/http';
  3. import { Observable } from 'rxjs/Observable';
  4. import 'rxjs/add/operator/map';
  5. import 'rxjs/add/operator/do';
  6. @Injectable()
  7. export class CommonService {
  8. constructor(private http: Http) { }
  9. saveUser(user){
  10. return this.http.post('http://localhost:8080/api/SaveUser/', user)
  11. .map((response: Response) =>response.json())
  12. }
  13. GetUser(){
  14. return this.http.get('http://localhost:8080/api/getUser/')
  15. .map((response: Response) => response.json())
  16. }
  17. deleteUser(id){
  18. return this.http.post('http://localhost:8080/api/deleteUser/',{'id': id})
  19. .map((response: Response) =>response.json())
  20. }
  21. }
Step 12

Now, write the View code in app.module.ts file.
  1. import { BrowserModule } from '@angular/platform-browser';
  2. import { NgModule } from '@angular/core';
  3. import { HttpModule } from '@angular/http';
  4. import { FormsModule } from '@angular/forms';
  5. import { AppComponent } from './app.component';
  6. import {CommonService} from './common.service';
  7. @NgModule({
  8. declarations: [
  9. AppComponent
  10. ],
  11. imports: [
  12. BrowserModule,HttpModule,FormsModule,
  13. ],
  14. providers: [CommonService],
  15. bootstrap: [AppComponent]
  16. })
  17. export class AppModule { }
Step 13

Code for app.component.html.
  1. <form #userForm="ngForm" (ngSubmit)="onSave(userForm.value)" novalidate>
  2. <p>Is "myForm" valid? {{userForm.valid}}</p>
  3. <table border='1'>
  4. <tr>
  5. <td>name</td>
  6. <td>
  7. <input name="id" type="hidden" [(ngModel)]="id" />
  8. <input name="name" type="text" required [(ngModel)]="name" />
  9. </td>
  10. </tr>
  11. <tr>
  12. <td>address</td>
  13. <td> <input name="address" required type="text" [(ngModel)]="address" /></td>
  14. </tr>
  15. <tr>
  16. <td colspan="2">
  17. <input type="submit" value="{{valbutton}}" />
  18. </td>
  19. </tr>
  20. </table>
  21. </form>
  22. <table border='1'>
  23. <tr>
  24. <td>Id</td>
  25. <td>Name</td>
  26. <td>Address</td>
  27. <td>Edit</td>
  28. <td>Delete</td>
  29. </tr>
  30. <tr *ngFor="let kk of Repdata;let ind = index">
  31. <td>{{ind + 1}}</td>
  32. <td>{{kk.name}}</td>
  33. <td>{{kk.address}}</td>
  34. <td><a (click)="edit(kk)" style="color:blueviolet">Edit</a></td>
  35. <td><a (click)="delete(kk._id)" style="color:blueviolet">Delete</a> </td>
  36. </tr>
  37. </table>
Step 14

Write this code in app.component.ts and remove the existing code from this file.
  1. import { Component, OnInit } from '@angular/core';
  2. import {FormGroup,FormControl,Validators,FormsModule, } from '@angular/forms';
  3. import {CommonService} from './common.service';
  4. import {Http,Response, Headers, RequestOptions } from '@angular/http';
  5. @Component({
  6. selector: 'app-root',
  7. templateUrl: './app.component.html',
  8. styleUrls: ['./app.component.css']
  9. })
  10. export class AppComponent {
  11. constructor(private newService :CommonService,) { }
  12. Repdata;
  13. valbutton ="Save";
  14. ngOnInit() {
  15. this.newService.GetUser().subscribe(data => this.Repdata = data)
  16. }
  17. onSave = function(user,isValid: boolean) {
  18. user.mode= this.valbutton;
  19. this.newService.saveUser(user)
  20. .subscribe(data => { alert(data.data);
  21. this.ngOnInit();
  22. }
  23. , error => this.errorMessage = error )
  24. }
  25. edit = function(kk) {
  26. this.id = kk._id;
  27. this.name= kk.name;
  28. this.address= kk.address;
  29. this.valbutton ="Update";
  30. }
  31. delete = function(id) {
  32. this.newService.deleteUser(id)
  33. .subscribe(data => { alert(data.data) ; this.ngOnInit();}, error => this.errorMessage = error )
  34. }
  35. }
We are almost done for performing select, insert, update, delete operation. Now, let us run two servers. The first one is Angular application with command ng server-o and the second one is to open node.js server.
We seen the output on borwser port 4200.

Summary

In this article, we learned how to create CRUD application with Angular 5 and node. I hope you enjoyed this article. If you have any query related to this code, please comment in the comments section.