You are on page 1of 39

21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

Home  Angular 

ANGULAR

Angular 6 CRUD Example | MEAN Stack Tutorial


Angular 6 CRUD Tutorial With Example From Scratch

By Krunal Last updated Nov 4, 2018

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.

Eco Villas Carmen de Apicalá


Lotes urbanizados de 8.900 m2

Se entregan con urbanismo completo.


Compra ya el tuyo y construyas tu casa
ecológicas.
lariveradesantafe.com

ABRIR

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 1/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

10 Movies With Surprising Hidden Meanings


FEATURED

If you want to learn advance about Angular and Node.js then check out below course.
This course has a brief introduction about Angular and Node.js and how they can
work together. It is a complete practical example of Angular and Node.js. I also found
it very useful.
The Complete Angular, React & Node Guide Airbnb Style App

Content Overview [hide]

1 Angular 6 Release
2 Tools For This Tutorial
3 Angular 6 CRUD Example | MEAN Stack Tutorial
4 Step1: Create Angular 6 Project.
5 Step 2: Install Bootstrap 4.
6 Step 3: Create components.
7 Step 4: Con gure the routing.
8 Step 5: Add Navigation.
9 Step 6: Add  Angular Routing Progress Indicator.
10 Step 7: Create a form.
11 Step 8: Con gure HttpClientModule.
12 Step 9: Create ad unit service to send http requests.
13 Step 10: Create Node.js, Express, and MongoDB.
14 Step 11: Create Express routes for our application.
15 Step 12: Add ReactiveFormsModule at the Angular.
16 Step 13: Display the data on the frontend.
17 Step 14: Edit Form and Update the Data.
18 Steps To Follow Github Code

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


https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 2/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack 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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 3/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

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

@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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 4/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

All the components are created inside components folder.

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

Step 4: Con gure the routing.


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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 5/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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  le.


Ad

WP 2019 Free Beta Theme

VISIT SITE

// app.module.ts

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

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

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

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

Now, you can see the components based on routes.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 6/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

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.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 7/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

npm install rxjs-compat --save

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

Our goal of this tutorial is that, when we navigate to di erent 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 le.

// 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  le.

@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  le.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 8/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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  le. We need to add
<ng2-slim-loading-bar> directive.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 9/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

<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 le, and you can see the routing indicator above navigation bar.

Step 7: Create a form.


Inside create.component.html le, 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>

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 10/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

Step 8: Con gure HttpClientModule.


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

// 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  le looks like this.

// adunit.service.ts

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

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

constructor() { }
}

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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 11/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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 le 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 le. So I am installing the nodemon
server. What it does is that, when I modify the server.js le, it restarts the node.js server
automatically.

npm install nodemon --save-dev

Switch to newly created server.js  le 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.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 12/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

mongod

Now, I have downloaded the MongoDB client from Studio3T.

So, Now, I have connected to the database.

Create one con g folder inside project root. In that create one le called DB.js.

// DB.js

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

Import this  DB.js  le inside our  server.js  le 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  le to connect our MongoDB application to


the Node.js server.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 13/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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 le 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 le.

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.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 14/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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 le called adunit.route.js.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 15/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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");
});
}
https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 16/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

});
});

// 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 le inside a server.js  le.

// server.js

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

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

So, our nal server.js  le 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);
});

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 17/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

Step 12: Add ReactiveFormsModule at the


Angular.
Inside app.module.ts  le, 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 rst write the form HTML in
the create.component.html. 

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 18/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

<!-- 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_na
me" #unit_name/>
</div>
<div *ngIf="angForm.controls['unit_name'].invalid && (angForm.controls['unit_nam
e'].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_p
rice" #unit_price/>
</div>
<div *ngIf="angForm.controls['unit_price'].invalid && (angForm.controls['unit_pric
e'].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]="angFor
m.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  le.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 19/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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  le.

So, let us create that.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 20/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

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

Now, ll the values and submit the form.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 21/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack 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.

Step 13: Display the data on the frontend.


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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 22/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

<!-- 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></t
d>
<td><a [routerLink]="" class="btn btn-danger">Delete</a></td>
</tr>
</tbody>
</table>

Now, inside index folder, create one le 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  le, we need to write the function that fetches the units
data from the MongoDB database and display at the Angular application.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 23/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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  le and AdUnit.ts  le inside an


index.component.ts  le.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 24/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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;
});
}
}

Step 14: Edit Form and Update the Data.


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

So rst, edit.component.html form looks like this.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 25/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

<!-- 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_na
me" #unit_name [(ngModel)] = "adunit.unit_name"/>
</div>
<div *ngIf="angForm.controls['unit_name'].invalid && (angForm.controls['unit_nam
e'].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_p
rice" #unit_price [(ngModel)] = "adunit.unit_price"/>
</div>
<div *ngIf="angForm.controls['unit_price'].invalid && (angForm.controls['unit_pric
e'].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]="ang
Form.invalid" class="btn btn-primary">Update Unit</button>
</div>
</form>
</div>
</div>

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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 26/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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  le.

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 27/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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  le, 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'));
}

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 28/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

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

// 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 nd 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 de ne click event on the delete button inside  an


index.component.html  le.

<!-- 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></t
d>
<td><button (click)="deleteAdUnit(adunit._id)" class="btn btn-danger">Delete</
button></td>
</tr>

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

// index.component.ts

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

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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 29/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

// 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

 Angular Express js MEAN Stack mongodb Node.js

Krunal - 516 Posts - 176

Comments

Krunal Lathiya is From India, and he is an Information Technology Engineer. By


profession, he is the latest web and mobile technology adapter, freelance developer,
Machine Learning, Arti cial Intelligence enthusiast, and primary Author of this blog.

WP 2019 Free Beta Theme


Early Access to All Features in Beta.Try Now Our Incredible Page OPEN
Builder ColibriWPTheme
report this ad

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 30/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

54 COMMENTS

Jylac Says  11 months ago

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

AnassL Says  11 months ago

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

It looks like you’re using ngModel on the same form eld 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 ()

Shruthi Says  10 months ago

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

Krunal Says  10 months ago

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

Lahiru Mahagamage Says  7 months ago

Try disabling your adblocker. That worked for me

Venkat Says  10 months ago

Hi Krunal, I am also getting the same error as posted by Shruthi.


Can you please help?

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 31/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

Krunal Says  10 months ago

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

Faiz Ahmed Says  8 months ago

Please do a tutorial on Angular 6 authentication with Firebase and


AngularFire please

Krunal Says  8 months ago

Thanks!! I will try my best to do that.

Monica Says  3 months ago

Check your server.js le and model,con g and routes folder location


(https://github.com/KrunalLathiya/Angular6CRUDTutorial ) as given. mongod and
nodemon server should be running

Tom Says  10 months ago

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 di erences between my
code and the repo code with di .

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.

Jeff Says  10 months ago

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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 32/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

https://stackover ow.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’,
‘pre ightContinue’: false
}));

Fix3: disable web security in chrome


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

Rad Says  8 months ago

working for me after turn o ads block extension

Lahiru Mahagamage Says  7 months ago

Exactly what Rad Says… Excuse the pun. but it’s the adblocker that stops
data from sending to the db.

Sagun Chauhan Says  4 months ago

Im having same error as many

||| Http failure response for http (url) 404 not found

David L Belisle Says  9 months ago

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, speci cally you should check
for Ad Blocker settings in Chrome as well as any plugins (mine was Avira Browser
Safety plugin.)

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 33/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

Tom Says  10 months ago

After some testing with di erent 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?

Krunal Says  10 months ago

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

Dave Says  10 months ago

Same here. However with Firefox Developer Edition it works ne.


Perhaps something changed with the last version of FF (I did update FF but not FFD)?
Thanks

Mary Raichel Paulson Says  10 months ago

Thank you very much. This is so helpfull

Jeff Says  10 months ago

Looks like some people are getting this error.

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

Any help to get around this?

Arif Iqbal Says  10 months ago

Many thanks for this great tutorial.

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

Vrushang Says  10 months ago

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?

Krunal Says  10 months ago

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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 34/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

Björn Says  9 months ago

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

Krunal Says  9 months ago

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

Alex Says  9 months ago

Hey what am i missing in this package.json le. 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”

Jibin Says  9 months ago

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 le type.
| RouterModule.forRoot(routes)
| ],
|;
|
how this x it

Sungki Scott Lee Says  9 months ago

Hey, nice tutorial,, thanks


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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 35/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

Coded Says  9 months ago

This help me out. Thanks

KPS Says  7 months ago

Thanks for edit!

Pramod Says  6 months ago

Thanks for the correction.

Mohammad Says  8 months ago

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

Rad Says  8 months ago

Call enableProdMode() to enable the production mode.

Murugan Says  8 months ago

Nice article.

How to refresh automatically?


Thank You

Fritas Says  8 months ago

Thank you for Your Tuto , but i don t nd the path of server.js ? could please help me

Giang Says  8 months ago

i cant start node js server with nodemon server what i can do

RadRouached Says  8 months ago

The local installation of nodemon can be run by calling: npx nodemon server

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 36/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

Fenitra Says  8 months ago

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!

Krunal Says  8 months ago

Thanks!! I will try my best to do that

Faiz Ahmed Says  8 months ago

Please do a tutorial on Angular 6 authentication with Firebase and AngularFire please

Omar Says  8 months ago

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?

Luc Says  7 months ago

Hi Thanks for the great trutorial.

But can you tell me how to connect an hosted MongoDB environment?

Thanks!

Luc Says  7 months ago

Hi, thanks for this clear tutorial.

But how to make a connection to the hosted environment on mongodb.com?

Dominic Says  7 months ago

getting 404 Bad Request – related to addProducts(x, x) {} any help?

Abbas Says  6 months ago

thank you for this tutorial, perfect .. it works all well plz add search lter for unit in the unit list

Prasanta Says  6 months ago

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

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 37/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

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

Christopher Crisson Says  5 months ago

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

Christopher Says  5 months ago

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

Katheeja Says  4 months ago

can you please help on how to display data from database to angular using oracle?

Pranali Mejari Says  3 months ago

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.

VIJAYAKUMAR Says  3 months ago

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 38/39
21/4/2019 Angular 6 CRUD Example | MEAN Stack Tutorial

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…

Cihan Says  2 months ago

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

Cihan Says  2 months ago

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

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

© 2017-2019 AppDividend. All rights reserved

https://appdividend.com/2018/05/27/angular-6-crud-example-mean-stack-tutorial/ 39/39

You might also like