Angular 6 CRUD: How to Create MEAN Stack Application

In this tutorial, I will teach you the Angular 6 CRUD Example. I will use Angular, MongoDB, Node.js, and Express.js for this project, also called the MEAN Stack web application. First, we make a simple Angular CRUD web tutorial, which can create, read, update, and delete ad units. Then, we build the frontend in Angular and create a backend rest api using Node.js, Express, and MongoDB. If you are new to Angular 6, check out this tutorial: Angular 6 Tutorial With Example using Angular CLI.

Angular 6 Release

There are some changes in the latest Angular version, and its core depends on the following.

  1. TypeScript 2.7
  2. RxJS 6.0.0

We will install Angular 6 using Angular CLI, and both the CLI and generated project have dependencies that require Node 8.9 or higher, together with NPM 5.5.1 or higher.

Tools For This Tutorial

The following tools, frameworks,  libraries are required for this tutorial:

  1. Node.js 8.9 or higher.
  2. Angular CLI
  3. MongoDB
  4. Express
  5. Terminal or Bash or CMD
  6. Editor or IDE(Mine is Visual Studio Code)

To update NPM, you can run the following command in the terminal.

# for mac

sudo npm install -g npm@latest

# for windows in admin mode

npm install -g npm@latest

You can uninstall the previous version of Angular CLI using the following command.

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli

# Mac users put sudo at the start of the command which has -g flag.

# Windows users, open the CMD in admin mode and type the following command

Angular 6 CRUD Example | MEAN Stack Tutorial

Okay, create a local project using the following command.

Step1: Create an Angular 6 Project.

ng new ng6crud

Go into the project folder.

cd ng6crud

Now, start the Angular 6 application using the following command.

ng serve --open

It compiles and opens up the browser at this URL: http://localhost:4200

Step 2: Install Bootstrap 4.

Okay, now install bootstrap 4 using the following command.

npm install bootstrap --save

Now, add the following line inside the src >> styles.css file.

@import "~bootstrap/dist/css/bootstrap.min.css"

Okay, now we can use the bootstrap 4 classes.

Step 3: Create components.

Create the components folder inside the app folder.

Okay, now generate components using the following command.

ng g c components/create --spec=false
ng g c components/index --spec=false
ng g c components/edit --spec=false

 

Angular 6 CRUD Example | MEAN Stack Tutorial

All the components are created inside the components folder.

The app.module.ts file will be automatically updated.

Step 4: Configure the routing.

Inside the app.module.ts file, create one array called routes and then add the object that contains the route path and route component. Also, import the RouterModule and Routes component.

// app.module.ts

import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'create',
    component: CreateComponent
  },
  {
    path: 'edit/:id',
    component: EditComponent
  },
  {
    path: 'index',
    component: IndexComponent
  }
];

Now, register these routes inside an app.module.ts file.

// app.module.ts

imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
],

Now, we can include the <router-outlet> inside an app.component.html file.

<!-- app.component.html -->

<div>
  <router-outlet></router-outlet>
</div>

Now, you can see the components based on routes.

For example, if you browse http://localhost:4200/create, you can see “create works!” in your browser.

Step 5: Add Navigation.

Add the navigation and change the app.component.html outlook due to bootstrap classes.

<!-- app.component.html -->

<nav class="navbar navbar-expand-sm bg-light">
  <div class="container-fluid">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a routerLink="create" class="nav-link" routerLinkActive="active">
          Create Ad Units
        </a>
      </li>
      <li class="nav-item">
        <a routerLink="index" class="nav-link" routerLinkActive="active">
          All Ad Units
        </a>
      </li> 
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

Step 6: Add the Angular Routing Progress Indicator.

Now, we need to install a third-party package. Unfortunately, as of now, third-party packages are not supported by Angular 6, so we need to install one library called rxjs-compat.

npm install rxjs-compat --save

Next, install the ng2-slim-loading-bar library.

The goal of this tutorial is that when we navigate to different routing components, we see the loading indicator. So for that, we need to install an ng2-slim-loading-bar library. To install using the following cmd.

npm install ng2-slim-loading-bar --save

Next, register this module inside an app.module.ts file.

// app.module.ts

import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';

imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    SlimLoadingBarModule
 ],

The next step is, include the styling that comes with the library inside the src  >>  styles.css file.

@import "~bootstrap/dist/css/bootstrap.min.css";
@import "../node_modules/ng2-slim-loading-bar/style.css";

Now, write the following code inside an app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import {SlimLoadingBarService} from 'ng2-slim-loading-bar';
import { NavigationCancel,
  Event,
  NavigationEnd,
  NavigationError,
  NavigationStart,
  Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(private _loadingBar: SlimLoadingBarService, private _router: Router) {
    this._router.events.subscribe((event: Event) => {
      this.navigationInterceptor(event);
    });
  }
  private navigationInterceptor(event: Event): void {
    if (event instanceof NavigationStart) {
      this._loadingBar.start();
    }
    if (event instanceof NavigationEnd) {
      this._loadingBar.complete();
    }
    if (event instanceof NavigationCancel) {
      this._loadingBar.stop();
    }
    if (event instanceof NavigationError) {
      this._loadingBar.stop();
    }
  }
}

Okay, now write the following code in the app.component.html file. We need to add <ng2-slim-loading-bar> directive.

<ng2-slim-loading-bar color="blue"></ng2-slim-loading-bar>
<nav class="navbar navbar-expand-sm bg-light">
  <div class="container-fluid">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a routerLink="create" class="nav-link" routerLinkActive="active">
          Create Ad Units
        </a>
      </li>
      <li class="nav-item">
        <a routerLink="index" class="nav-link" routerLinkActive="active">
          All Ad Units
        </a>
      </li> 
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

Save the file, and you can see the routing indicator above the navigation bar.

Step 7: Create a form.

Inside the create.component.html file, write the following code.

<!-- create.component.html -->

<div class="card">
  <div class="card-body">
    <form>
      <div class="form-group">
        <label class="col-md-4">Unit Name</label>
        <input type="text" class="form-control" name="unit_name"/>
      </div>
      <div class="form-group">
        <label class="col-md-4">Unit Price</label>
        <input type="text" class="form-control" name="unit_price"/>
        </div>
        <div class="form-group">
          <button type="submit" class="btn btn-primary">Create Unit</button>
        </div>
    </form>
  </div>
</div>

 

Angular 6 CRUD Tutorial

Step 8: Configure HttpClientModule.

Register the HttpCientModule inside an app.module.ts file.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    SlimLoadingBarModule,
    HttpClientModule
 ],

Step 9: Create an ad unit service to send http requests.

Type the following command in your terminal.

ng g service adunit --spec=false

So, your primary adunit.service.ts file looks like this.

// adunit.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AdunitService {

  constructor() { }
}

Now, import the adunit.service.ts file into the app.module.ts file.

// app.module.ts

import { AdunitService } from './adunit.service';

providers: [ AdunitService ],

Step 10: Create Node.js, Express, and MongoDB.

The next step is to create Node.js, Express, and MongoDB backend to store the data. Create one file in the project root folder called server.js

We need to install the express.js web framework and other dependencies via a node package manager(NPM), so let us do that.

npm install --save express body-parser cors mongoose

I do not restart the node server each time; I change the file. So I am installing the nodemon server. What it does is that when I modify the server.js file, it restarts the node.js server automatically.

npm install nodemon --save-dev

Please switch to the newly created server.js file and enter the following code into it.

// server.js

let express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose');

    const app = express();
    var port = process.env.PORT || 4000;

    var server = app.listen(function(){
        console.log('Listening on port ' + port);
    });

The next thing is to connect the MongoDB database with our node.js application.

If you have not installed the MongoDB database, then install it and then start the mongodb server.

Type the following command to start the MongoDB server.

mongod

Now, I have downloaded the MongoDB client from Studio3T.

MongoDB Client

 

So, Now, I have connected to the database.

Create one config folder inside the project root. In that, create one file called DB.js.

// DB.js

module.exports = {
    DB: 'mongodb://localhost:27017/ng6crud'
 };

Import this DB.js file inside our server.js file and use the mongoose library to set up the database connection with MongoDB. We can also use Mongoose to save the data in the database using Mongoose ORM.

Write the following code inside the server.js file to connect our MongoDB application to the Node.js server.

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./config/DB');

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );

    const app = express();
    app.use(bodyParser.json());
    app.use(cors());
    const port = process.env.PORT || 4000;

    const server = app.listen(port, function(){
     console.log('Listening on port ' + port);
    });

Save a file and go to a terminal and start the node.js server using the following command. You can also write this command inside the package.json file.

nodemon server

Now, We have a total of three servers are running.

  1. Angular Development Server.
  2. Node.js Server.
  3. Mongodb Server.

Step 11: Create Express routes for our application.

Now, we need to create two folders inside the root folder called routes and models.

In the models folder, create one model called AdUnit.js.

// AdUnit.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for AdUnits
let AdUnit = new Schema({
  unit_name: {
    type: String
  },
  unit_price: {
    type: Number
  }
},{
    collection: 'adunits'
});

module.exports = mongoose.model('AdUnit', AdUnit);

In the routes folder, create one file called adunit.route.js.

// adunit.route.js

const express = require('express');
const app = express();
const adUnitRoutes = express.Router();

// Require AdUnit model in our routes module
let AdUnit = require('../models/AdUnit');

// Defined store route
adUnitRoutes.route('/add').post(function (req, res) {
  let adUnit = new AdUnit(req.body);
  adUnit.save()
    .then(game => {
    res.status(200).json({'adUnit': 'AdUnit in added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
adUnitRoutes.route('/').get(function (req, res) {
    AdUnit.find(function (err, adUnits){
    if(err){
      console.log(err);
    }
    else {
      res.json(adUnits);
    }
  });
});

// Defined edit route
adUnitRoutes.route('/edit/:id').get(function (req, res) {
  let id = req.params.id;
  AdUnit.findById(id, function (err, adUnit){
      res.json(adUnit);
  });
});

//  Defined update route
adUnitRoutes.route('/update/:id').post(function (req, res) {
    AdUnit.findById(req.params.id, function(err, adUnit) {
    if (!adUnit)
      return next(new Error('Could not load Document'));
    else {
        adUnit.unit_name = req.body.unit_name;
        adUnit.unit_price = req.body.unit_price;

        adUnit.save().then(adUnit => {
          res.json('Update complete');
      })
      .catch(err => {
            res.status(400).send("unable to update the database");
      });
    }
  });
});

// Defined delete | remove | destroy route
adUnitRoutes.route('/delete/:id').get(function (req, res) {
    AdUnit.findByIdAndRemove({_id: req.params.id}, function(err, adUnit){
        if(err) res.json(err);
        else res.json('Successfully removed');
    });
});

module.exports = adUnitRoutes;

I have written all the logic to create, read, update, and delete the data from the mongodb database.

Include this adunit.route.js route file inside a server.js file.

// server.js

const adUnitRoutes = require('./routes/adunit.route');

app.use('/adunits', adUnitRoutes);

So, our final server.js file looks like this.

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./config/DB');

    const app = express();

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );
    const adUnitRoutes = require('./routes/adunit.route');

    app.use(bodyParser.json());
    app.use(cors());
    const port = process.env.PORT || 4000;

    app.use('/adunits', adUnitRoutes);

    const server = app.listen(port, function(){
     console.log('Listening on port ' + port);
    });

Step 12: Add ReactiveFormsModule at the Angular.

Inside the app.module.ts file, add the ReactiveFormsModule from @angular/forms package.

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    SlimLoadingBarModule,
    HttpClientModule,
    ReactiveFormsModule
  ],

Then, we are validating the forms. So first, write the form HTML in the create.component.html. 

<!-- create.component.html -->

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Unit Name</label>
        <input type="text" class="form-control" name="unit_name" formControlName="unit_name" #unit_name/>
      </div>
      <div *ngIf="angForm.controls['unit_name'].invalid && (angForm.controls['unit_name'].dirty || angForm.controls['unit_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['unit_name'].errors.required">
          Unit Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Unit Price</label>
        <input type="text" class="form-control" name="unit_price" formControlName="unit_price" #unit_price/>
      </div>
      <div *ngIf="angForm.controls['unit_price'].invalid && (angForm.controls['unit_price'].dirty || angForm.controls['unit_price'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['unit_price'].errors.required">
          Unit Price is required.
        </div>
      </div>
      <div class="form-group">
        <button (click)="addAdUnit(unit_name.value, unit_price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Create Unit</button>
      </div>
    </form>
  </div>
</div>

Also, we need to write the logic of the form validation in the create.component.ts file.

// create.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { AdunitService } from '../../adunit.service';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  angForm: FormGroup;

  constructor(private adunitservice: AdunitService, private fb: FormBuilder) { 
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      unit_name: ['', Validators.required ],
      unit_price: ['', Validators.required ]
   });
  }

  addAdUnit(unit_name, unit_price) {
    this.adunitservice.addAdUnit(unit_name, unit_price);
}

  ngOnInit() {
  }

}

Here, we have used the addAdUnit() function but not created inside an adunit.service.ts file.

So, let us create that.

// adunit.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AdunitService {

  uri = 'http://localhost:4000/adunits';

  constructor(private http: HttpClient) { }

  addAdUnit(unit_name, unit_price) {
    const obj = {
      unit_name: unit_name,
      unit_price: unit_price
    };
    this.http.post(`${this.uri}/add`, obj)
        .subscribe(res => console.log('Done'));
  }

}

Okay, now go to this URL and check the validation: http://localhost:4200/create.

 

Angular 6 Form Validation Tutorial

Now, fill in the values and submit the form.

Angular 6 Tutorial

 

You can see in the console that we have successfully saved the values in the MongoDB database.

Now, you can see it in the MongoDB database.

MongoDB CRUD

 

Step 13: Display the data on the front end.

In the index.component.html file, write the following code.

<!-- index.component.html -->

<table class="table table-hover">
  <thead>
  <tr>
      <td>Ad Unit Name</td>
      <td>Ad Unit Price</td>
      <td colspan="2">Actions</td>
  </tr>
  </thead>

  <tbody>
      <tr *ngFor="let adunit of adunits">
          <td>{{ adunit.unit_name }}</td>
          <td>{{ adunit.unit_price }}</td>
          <td><a [routerLink]="['/edit', adunit._id]" class="btn btn-primary">Edit</a></td>
          <td><a [routerLink]="" class="btn btn-danger">Delete</a></td>
      </tr>
  </tbody>
</table>

Now, inside the index folder, create one file called AdUnit.ts. AdUnit.ts is an interface, which tells Angular 6 that, what kind of backend data there is that we need to display at the Angular 6 frontend. For example, we are using the Strict TypeScript type checking feature.

// AdUnit.ts

export interface AdUnit {
    id: Number;
    unit_name: String;
    unit_price: Number;
}

Inside the adunit.service.ts file, we need to write the function that fetches the unit data from the MongoDB database and displays it at the Angular application.

// adunit.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AdUnit } from './components/index/AdUnit';

@Injectable({
  providedIn: 'root'
})
export class AdunitService {

  uri = 'http://localhost:4000/adunits';

  constructor(private http: HttpClient) { }

  addAdUnit(unit_name, unit_price) {
    const obj = {
      unit_name: unit_name,
      unit_price: unit_price
    };
    this.http.post(`${this.uri}/add`, obj)
        .subscribe(res => console.log('Done'));
  }

  getAdUnits() {
    return this
           .http
           .get(`${this.uri}`);
    }

}

Now, we need to include this adunit.service.ts file and AdUnit.ts file inside an index.component.ts file.

// index.component.ts

import { Component, OnInit } from '@angular/core';
import { AdUnit } from './AdUnit';
import { AdunitService } from '../../adunit.service';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {

  adunits: AdUnit[];

  constructor(private adunitservice: AdunitService) { }

  ngOnInit() {
    this.adunitservice
      .getAdUnits()
      .subscribe((data: AdUnit[]) => {
      this.adunits = data;
    });
  }
}

 

MEAN Stack Tutorial

Step 14: Edit Form and Update the Data.

Okay, we need to fetch the data from the MongoDB database using _id wise and display that data in the edit.component.html file.

So first, the edit.component.html form looks like this.

<!-- edit.component.html -->

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Unit Name</label>
        <input type="text" class="form-control" name="unit_name" formControlName="unit_name" #unit_name [(ngModel)] = "adunit.unit_name"/>
      </div>
      <div *ngIf="angForm.controls['unit_name'].invalid && (angForm.controls['unit_name'].dirty || angForm.controls['unit_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['unit_name'].errors.required">
          Unit Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Unit Price</label>
        <input type="text" class="form-control" name="unit_price" formControlName="unit_price" #unit_price [(ngModel)] = "adunit.unit_price"/>
      </div>
      <div *ngIf="angForm.controls['unit_price'].invalid && (angForm.controls['unit_price'].dirty || angForm.controls['unit_price'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['unit_price'].errors.required">
          Unit Price is required.
        </div>
      </div>
      <div class="form-group">
        <button (click)="updateAdUnit(unit_name.value, unit_price.value)" [disabled]="angForm.invalid" class="btn btn-primary">Update Unit</button>
      </div>
    </form>
  </div>
</div>

Inside the edit.component.ts file, write the following code.

// edit.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { AdUnit } from '../index/AdUnit';
import { AdunitService } from '../../adunit.service';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {

  adunit: any = {};
  angForm: FormGroup;

  constructor(private route: ActivatedRoute,
    private router: Router,
    private adunitservice: AdunitService,
    private fb: FormBuilder) {
      this.createForm();
    }
    createForm() {
      this.angForm = this.fb.group({
             unit_name: ['', Validators.required ],
              unit_price: ['', Validators.required ]
         });
      }

    ngOnInit() {
      this.route.params.subscribe(params => {
        this.adunitservice.editAdUnit(params['id']).subscribe(res => {
          this.adunit = res;
      });
    });
  }
}

Also, you need to create an editAdUnit function inside an adunit.service.ts file.

// adunit.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AdUnit } from './components/index/AdUnit';

@Injectable({
  providedIn: 'root'
})
export class AdunitService {

  uri = 'http://localhost:4000/adunits';

  constructor(private http: HttpClient) { }

  addAdUnit(unit_name, unit_price) {
    const obj = {
      unit_name: unit_name,
      unit_price: unit_price
    };
    this.http.post(`${this.uri}/add`, obj)
        .subscribe(res => console.log('Done'));
  }

  getAdUnits() {
    return this
           .http
           .get(`${this.uri}`);
}

editAdUnit(id) {
  return this
            .http
            .get(`${this.uri}/edit/${id}`);
  }
}

Now, you can see the edited data from the MongoDB database.

Inside the adunit.service.ts file, we need to write the function that updates the data.

// adunit.service.ts

updateAdUnit(unit_name, unit_price, id) {

  const obj = {
    unit_name: unit_name,
    unit_price: unit_price
  };
  this
    .http
    .post(`${this.uri}/update/${id}`, obj)
    .subscribe(res => console.log('Done'));
}

Okay, now write the updateAdUnit() function inside edit.component.ts file.

// edit.component.ts

updateAdUnit(unit_name, unit_price) {
   this.route.params.subscribe(params => {
      this.adunitservice.updateAdUnit(unit_name, unit_price, params['id']);
      this.router.navigate(['index']);
   });
}

Finally, you can be able to update the data.

So, if you find no error on the console, then you can successfully update the data.

 I have already written the edit and update service to make an API call. So till now, Create, Read, Update is complete of this Angular 6 CRUD Example Tutorial. Now, take a look at Delete.

Now, we need to define the click event on the delete button inside an index.component.html file.

<!-- index.component.html -->

<tr *ngFor="let adunit of adunits">
          <td>{{ adunit.unit_name }}</td>
          <td>{{ adunit.unit_price }}</td>
          <td><a [routerLink]="['/edit', adunit._id]" class="btn btn-primary">Edit</a></td>
          <td><button (click)="deleteAdUnit(adunit._id)"  class="btn btn-danger">Delete</button></td>
</tr>

Now, write the deleteAdUnit function inside an index.component.ts file.

// index.component.ts

deleteAdUnit(id) {
    this.adunitservice.deleteAdUnit(id).subscribe(res => {
      console.log('Deleted');
    });
  }

Finally, create deleteAdUnit() function inside adunit.service.ts file.

// adunit.service.ts

deleteAdUnit(id) {
    return this
              .http
              .get(`${this.uri}/delete/${id}`);
}

Finally, I Completed the delete functionality.

So, in this tutorial, we have complete the CRUD Functionality in Angular 6.

If you have any doubt about this Angular 6 CRUD Example, then ask in a comment below.

Github Code

Steps To Follow Github Code

  1. Clone the repository.
  2. Hit this command: npm install
  3. Start the MongoDB server.
  4. Start Node.js server using this command: nodemon server
  5. Start the Angular dev server using the following command: ng server –open
  6. Go to this URL: http://localhost:4200/create

56 thoughts on “Angular 6 CRUD: How to Create MEAN Stack Application”

  1. Good job, but got a console error when tried to use “Edit” template:

    It looks like you’re using ngModel on the same form field as formControlName.
    Support for using the ngModel input property and ngModelChange event with
    reactive form directives has been deprecated in Angular v6 and will be removed
    in Angular v7.

    For more information on this, see our API docs here:
    https://angular.io/api/forms/FormControlName#use-with-ngmodel

    And when I click on submit button, I get the following error:
    https://example.com/api/values/update/5 404 ()

    Reply
  2. POST http://localhost:4000/adunits/add 404 (Not Found) 4000/adunits/add:1

    core.js:1542 ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: “Not Found”, url: “http://localhost:4000/adunits/add”, ok: false, …}

    I got the above error while sending the data from form to db, could u help me out where exactly i should see

    Reply
  3. Hi Krunal, thanks for the concise but full-featured tutorial. Unfortunately I have the same problem as Venkat and Shruthi. I’ve checked the repo and I can’t see differences between my code and the repo code with diff.

    It it failing when trying to use the AdunitService addAdUnit() function. Here is the error:

    error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, … }
    headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
    message: “Http failure response for (unknown url): 0 Unknown Error”
    name: “HttpErrorResponse”
    ok: false
    status: 0
    statusText: “Unknown Error”
    url: null

    It seems that maybe url is null? Do you have any ideas?

    Thanks.

    Reply
  4. After some testing with different browsers, it seems that the error Venkat, Shruthi and I are getting only happens in Firefox. Opera and Chrome work perfectly. Does anyone have any idea why it’s only not working in Firefox?

    Reply
  5. Many thanks for this great tutorial.

    Can you please share some resource to deploy this app with current structure etc.

    Reply
  6. Hey krunal how can i execute two commands at a time?nodemon server and ng server -open.
    Cmd only alllows one at a time.What should i do?

    Reply
    • You need to type both the commands on different command line tabs. Not the same one. It will start two different servers, running on different ports.

      Reply
      • hi, i can not start the nodeman server with command “nodeman server”. the shell output was “Command not finde”. I must install the nodeman server globaly with following command that we can start it. sudo npm install -g nodemon –save

        Reply
  7. Hey what am i missing in this package.json file. it starts either server.js or ng serve, based on the order of command
    “version”: “0.0.0”,
    “scripts”: {
    “ng”: “ng”,
    “start”: “nodemon server.js && ng serve”,
    “build”: “ng build”,
    “test”: “ng test”,
    “lint”: “ng lint”,
    “e2e”: “ng e2e”

    Reply
  8. hi sir,
    i have this error ./src/app/app.module.ts
    Module parse failed: Unexpected token (53:0)
    You may need an appropriate loader to handle this file type.
    | RouterModule.forRoot(routes)
    | ],
    | ;
    |
    how this fix it

    Reply
  9. Hey, nice tutorial,, thanks
    1. typo
    getAdUnits() {
    return this
    .http
    .get(`${this.uri}/adunits`); ==> should be .get(`${this.uri}/`);
    }

    Reply
  10. Thank you for this helpful tutorial
    I have one question
    How can I publish this project to production server
    I build the angular project with ng build –prod but I don’t have any idea about nodejs
    Could you please explain this question

    Reply
  11. Super tuto! Grand merci à Vous! Est-ce que tu peux me guider pour l’utilisation de mysql au lieu de MongoDB? merci d’avance! J’adore votre tuto!

    Reply
  12. hello,

    i followed your tutorial and i am beginner in angular and node js.
    i am getting this error when i do submit add unit form. what is the issue here?

    Reply
  13. Hi I am getting the following error, when i click the .

    zone.js:2969 OPTIONS http://localhost:27017/adunits/add net::ERR_CONNECTION_RESET
    core.js:12632 ERROR
    HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: “Unknown Error”, url: null, ok: false, …}
    error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: “error”, …}
    headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
    message: “Http failure response for (unknown url): 0 Unknown Error”
    name: “HttpErrorResponse”
    ok: false
    status: 0
    statusText: “Unknown Error”
    url: null
    __proto__: HttpResponseBase

    when i check the link “http://localhost:27017/adunits/add” at browser I am getting the message

    “It looks like you are trying to access MongoDB over HTTP on the native driver port.”

    Reply
  14. I had the error many people seem to be getting when trying to connect to the database. My problem was with the AdUnit.js file inside the models directory. I was able to find it by checking the terminal tab running nodemon. Look for “[nodemon] app crashed – waiting for file changes before starting…”. Hope this helps someone.

    Reply
  15. I had the error many people seem to be getting when trying to connect to the database. My problem was with the AdUnit.js file inside the models directory. I was able to find it by checking the terminal tab running nodemon. Look for “[nodemon] app crashed – waiting for file changes before starting…”. Hope this helps someone.

    Reply
    • Katheeja,

      Did you solve a problem with Oracle DB connection?. If so Can you contact me? I desperately need to solve the same problem.

      Reply
  16. Hi Krunal,

    Thank you so much for great tutorial:-)
    I got some errors during coding, but solved them by R&D.

    Please keep continuing posting such knowledgeable tutorials, thanks again.

    Reply
  17. Hai, I am Run the program successfully, But It connected successfully in the database, But No Data send to the mongodb Collection… How i can solve this Problem…

    Reply
  18. ERROR
    HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: “Unknown Error”, url: “http://localhost:4000/adunits/add”, ok: false, …}
    error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: “error”, …}
    headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
    message: “Http failure response for http://localhost:4000/adunits/add: 0 Unknown Error”
    name: “HttpErrorResponse”
    ok: false
    status: 0
    statusText: “Unknown Error”
    url: “http://localhost:4000/adunits/add”
    __proto__: HttpResponseBase

    Reply
  19. Hi , i sent a post one hour ago. I solved that problem. server.js was not in the root directory and i didn’t run the nodeman server command. Also this article is great

    Reply
  20. Great explanation. I have one doubt,
    How can we show success messages like added, updated, deleted successfully using sweet alerts.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.