AppDividend
Latest Code Tutorials

Angular 6 CRUD Example | MEAN Stack Tutorial

Angular 6 CRUD Tutorial With Example From Scratch

24,260

Get real time updates directly on you device, subscribe now.

In this tutorial, I will teach you Angular 6 CRUD Example. I will use Angular, MongoDB, Node.js, and Express.js for this project, so this project is also called MEAN Stack web application. We make a simple Angular CRUD web tutorial, which can create, read, update and delete ad units. We build frontend in Angular and create a backend rest api using Node.js, Express, and MongoDB. If you are new to Angular 6 then 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 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 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 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

Related Posts
1 of 10

All the components are created inside components folder.

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

Step 4: Configure the routing.

Inside app.module.ts file, create one array called routes and then add the object that contains 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 then 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  Angular Routing Progress Indicator.

Now, we need to install third-party package. As of now, third-party packages are not supported to 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.

Our 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. So 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
 ],

Next step is, include the styling that comes with the library inside 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 navigation bar.

Step 7: Create a form.

Inside 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 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.

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

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

npm install --save express body-parser cors mongoose

I do not restart 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

Switch to 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 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 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 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 total 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 root folder called routes and models.

In 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 that can 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 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 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, till now, 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 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 in the MongoDB database.

MongoDB CRUD

 

Step 13: Display the data on the frontend.

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 index folder, create one file called AdUnit.ts. AdUnit.ts is an interface, which tells the Angular 6 that, what kind of backend data there is that we need to display at Angular 6 frontend. We are using the Strict TypeScript type checking feature.

// AdUnit.ts

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

Now, inside adunit.service.ts file, we need to write the function that fetches the units data from the MongoDB database and display 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}/adunits`);
    }

}

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, first, 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, 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 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 edit 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 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 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, Completed the delete functionality.

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

If you have any doubt in 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
25 Comments
  1. jylac says

    Great tutorial !
    But how to refresh the page after removing or editing an adunit ?
    Many thanks

  2. AnassL says

    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 ()

  3. Shruthi says

    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

    1. Krunal says

      I have checked my code again, it is working fine, please check the Github repo, if you have any doubt.

  4. venkat says

    Hi Krunal, I am also getting the same error as posted by Shruthi.
    Can you please help?

    1. Krunal says

      I have checked my code again, it is working fine, please check the Github repo, if you have any doubt. If all the servers are working fine then it should be working great!!

  5. Tom says

    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.

    1. Jeff says

      I also get this error. Well documented but none of the fixes below work for me. You might want to try some of them.

      https://stackoverflow.com/questions/47180634/i-get-http-failure-response-for-unknown-url-0-unknown-error-instead-of-actu

      Fix 1:
      Install the plugin for chrome,
      https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

      Fix 2:
      change
      app.use(cors());

      to

      app.use(cors({
      ‘allowedHeaders’: [‘sessionId’, ‘Content-Type’],
      ‘exposedHeaders’: [‘sessionId’],
      ‘origin’: ‘*’,
      ‘methods’: ‘GET,HEAD,PUT,PATCH,POST,DELETE’,
      ‘preflightContinue’: false
      }));

      Fix3: disable web security in chrome
      –disable-web-security –user-data-dir=c:\my\data

    2. David L Belisle says

      I also had this error, which was not a problem with the code. Instead, my browser was stopping the HTTP request because of browser settings, specifically you should check for Ad Blocker settings in Chrome as well as any plugins (mine was Avira Browser Safety plugin.)

  6. Tom says

    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?

    1. Krunal says

      I have not check that yet Tom, but will check and update it.

    2. Dave says

      Same here. However with Firefox Developer Edition it works fine.
      Perhaps something changed with the last version of FF (I did update FF but not FFD)? Thanks

  7. Mary Raichel Paulson says

    Thank you very much. This is so helpfull

  8. Jeff says

    Looks like some people are getting this error.

    https://stackoverflow.com/questions/48557390/angular-4-http-failure-response-for-unknown-url-0-unknown-error

    Any help to get around this?

  9. Arif Iqbal says

    Many thanks for this great tutorial.

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

  10. vrushang says

    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?

    1. Krunal says

      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.

      1. Björn says

        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

        1. Krunal says

          sudo npm install -g nodemon –save try this command.

  11. Alex says

    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”

  12. jibin says

    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

  13. sungki scott lee says

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

    1. Coded says

      This help me out. Thanks

  14. Mohammad says

    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

  15. Murugan says

    Nice article.

    How to refresh automatically?
    Thank You

Leave A Reply

Your email address will not be published.

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