Home » Angular 6 CRUD Operations Demo Example

Angular 6 CRUD Operations Demo Example

Today, We want to share with you Angular 6 CRUD Operations Demo Example.In this post we will show you Angular 6 CRUD Tutorial for beginners, hear for Angular 6 CRUD Operations Application and Example we will give you demo and example for implement.In this post, we will learn about Angular 6 CRUD Project Setup, Routing, Service with an example.

Angular 6 CRUD Operations Demo Example

There are the Following The simple About Angular 6 CRUD Operations Demo Example Full Information With Example and source code.

As I will cover this Post with live Working example to develop , so the some major files and Directory structures for this example is following below.

  • Angular 6 Install Angular CLI.
  • Angular 6 Project Setup
  • Angular 6 components
  • Angular 6 Configure Routing
  • Angular 6 Project
  • Add Bootstrap CSS
  • HttpClientModule in Angular 6
  • More..

Angular 6 CRUD Example Tutorial From Scratch

Step 1: Install Angular CLI in Angular 6 Project.

Install Angular CLI

npm install -g @angular/cli

create a local project in Angular 6

ng new angular6crud

Angular 6 start the application

ng serve --open

Step 2: Make three components.

components inside app folder

Simple Angular 6 CRUD Operations Demo Installations

Angular-6-CRUD-Example-Tutorial-From-Scratch
Angular-6-CRUD-Example-Tutorial-From-Scratch

Step 3: Configure the routing in Angular 6.

app.module.ts

// app.module.ts

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

//Angular 6 CRUD Operations Demo Routing
const routes:Routes = [
  { 
    path: 'create', 
    component: CreateComponent 
  },
  {
    path: 'edit/:id',
    component: EditComponent
  },
  { 
    path: 'index',
    component: IndexComponent
  }
]

register these routes

// app.module.ts

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

in Angular 6 router-outlet> inside an source code of app.component.html file

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

Step 4: Insert Bootstrap CSS.

src >> index.html

<link rel="stylesheet" href="assets/css/bootstrap.min.css">

app.component.html

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <ul class="nav navbar-nav">
      <li class="active">
        <a routerLink="create" routerLinkActive="active">
          Add Members
        </a>
      </li>    
    </ul>
  </div>
</nav>

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

Step 5: Create a HTML form in the make a component file.

create.component.html

<h2>Angular 6 CRUD Operations Demo</h2>
<div class="card">
    <div class="card-body">
      <form>
        <div class="form-group">
          <label class="col-md-4">Member Name</label>
          <input type="text" class="form-control" name="member_name"/>
        </div>
        <div class="form-group">
          <label class="col-md-4">Member Age</label>
          <input type="text" class="form-control" name="member_age"/>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-success">Add</button>
          </div>
      </form>
    </div>
  </div>

Step 6: Configure angular 6 HttpClientModule.

app.module.ts

// app.module.ts
//Angular 6 CRUD Operations Demo

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

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

step 7: Make services to send angular 6 http requests.

ng g service member

MemberService.ts

// MemberService.ts

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

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

  constructor() { }
}

member.service.ts

// member.service.ts

import { MemberService } from './member.service';

providers: [ MemberService ]

Step 8: Configure Node.js backend.

Node.js as well as MongoDB backend for Angular 6 CRUD Operations Demo

//express web framework
npm install --save express body-parser cors mongoose


//add nodemon server 
npm install nodemon --save-dev

app.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);
    });

DB.js

// DB.js

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

copy and paste the Angular 6 CRUD Operations Demo following source code inside the main file server.js In to connect step by step simple main MongoDB store database application to the main files like as Node.js server.

Read Also:  Angular 6 applications - Insert, Fetch , Edit - update , Delete Operations

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

node.js run command

nodemon server

And then, I have All the three main servers are running.

  • Angular Development Server.
  • simple Node.js Server
  • start Mongodb Server

Step 9: Make Express routes for angular 6 Web application.

Member.js

// Member.js

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

// Define collection and schema for Members
let Member = new Schema({
  name: {
    type: String
  },
  age: {
    type: Number
  }
},{
    collection: 'members'
});

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

member.route.js

// member.route.js

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

let Member = require('../models/Member');

memberRoutes.route('/add').post(function (request, response) {
  let member = new Member(request.body);
   member.save()
    .then(member => {
    response.status(200).json({'member': 'CoMemberin added successfully'});
    })
    .catch(err => {
    response.status(400).send("unable to save to database");
    });
});


memberRoutes.route('/').get(function (request, response) {
   Member.find(function (err, members){
    if(err){
      console.log(err);
    }
    else {
      response.json(members);
    }
  });
});

memberRoutes.route('/edit/:id').get(function (request, response) {
  let id = request.params.id;
  Member.findById(id, function (err, member){
      response.json(member);
  });
});

//  Defined update route
memberRoutes.route('/update/:id').post(function (request, response) {
   Member.findById(request.params.id, function(err, member) {
    if (!member)
      return next(new Error('Could not load Document'));
    else {
      member.name = request.body.name;
      member.age = request.body.age;

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

// Defined delete | remove | destroy route
memberRoutes.route('/delete/:id').get(function (request, response) {
   Member.findByIdAndRemove({_id: request.params.id}, function(err, member){
        if(err) response.json(err);
        else response.json('Successfully removed');
    });
});

module.exports = memberRoutes;

Add this simple Member.js model inside a main server.js file.

// server.js

const memberRoutes = require('./routes/member.route');

app.use('/members', memberRoutes);

server.js

// server.js

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

const memberRoutes = require('./routes/member.route');

    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());
    app.use('/members', memberRoutes);

const port = process.env.PORT || 4000;

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

Step :10 Insert ReactiveFormsModule at the Angular 6


// app.module.ts

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

imports: [
    ReactiveFormsModule
  ],

create.component.html

<div class="card">
    <div class="card-body">
      <form [formGroup]="memberFrm" novalidate>
        <div class="form-group">
          <label class="col-md-4">Member Name</label>
          <input type="text" class="form-control" formControlName="name" #name />
        </div>
        <div *ngIf="memberFrm.controls['name'].invalid && (memberFrm.controls['name'].dirty || memberFrm.controls['name'].touched)" class="alert alert-danger">
          <div *ngIf="memberFrm.controls['name'].errors.required">
            Name is required.
          </div>
        </div>
        <div class="form-group">
          <label class="col-md-4">Member Age</label>
          <input type="text" class="form-control" formControlName="age" #age/>
        </div>
        <div *ngIf="memberFrm.controls['age'].invalid && (memberFrm.controls['age'].dirty || memberFrm.controls['age'].touched)" class="alert alert-danger">
          <div *ngIf="memberFrm.controls['age'].errors.required">
            Age is required.
          </div>
        </div>
          <div class="form-group">
            <button (click)="addMember(name.value, age.value)" [disabled]="memberFrm.pristine || memberFrm.invalid" class="btn btn-success">Add</button>
          </div>
      </form>
    </div>
  </div>

create.component.ts

// create.component.ts

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

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

 title = 'Add Member';
  memberFrm: FormGroup;

  constructor(private memberservice: MemberService, private fb: FormBuilder) {
    this.createForm();
   }

   createForm() {
    this.memberFrm = this.fb.group({
      name: ['', Validators.required ],
      age: ['', Validators.required ]
   });
  }

  addMember(name, age) {
      this.memberservice.addMember(name, age);
  }

  ngOnInit() {
  }

}

member.service.ts

// member.service.ts

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

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

  constructor(private http: HttpClient) { }

  addMember(name, age) {
    const uri = 'http://localhost:4000/members/add';
    const obj = {
      name: name,
      age: age
    };
    this.http.post(uri, obj)
        .subscribe(response => console.log('Done'));
  }
}

Step 10: Listing the data content to the View Side.

index.component.html

<table class="table table-hover">
  <thead>
  <tr>
      <td>Member Name</td>
      <td>Member Age</td>
      <td colspan="2">Actions</td>
  </tr>
  </thead>

  <tbody>
      <tr *ngFor="let member of members">
          <td>{{ member.name }}</td>
          <td>{{ member.age }}</td>
          <td><a [routerLink]="['/edit', member._id]" class="btn btn-success">Edit</a></td>
          <td><a [routerLink]="" class="btn btn-danger">Delete</a></td>
      </tr>
  </tbody>
</table>

Member.ts

export interface Member {
    id: Number;
    name: String;
    age: Number;
}

member.service.ts

Read Also:  Angular 6 CRUD Tutorial Example From Scratch

And then, inside member.service.ts file, I should to simple a function that get the data from the latest light weight json based MongoDB database and listing at the first Angular 6 Application.

// member.service.ts

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

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

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

 	constructor(private http: HttpClient) { }

  	addMember(name, age) {
        const obj = {
          name: name,
          age: age
        };
        this
        	.http
        	.post(`${this.uri}/members/add`, obj)
            .subscribe(response => 
            	console.log('Done')
            );
  	}

  	getMembers() {
             return this
                    .http
                    .get(`${this.uri}/members`);
    	}
 }
}

index.component.ts

// index.component.ts

import { Component, OnInit } from '@angular/core';
import { Member } from './Member';
import { MemberService } from '../../member.service';

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

    members: Member[];

 	constructor(private memberservice: MemberService) { }

  	ngOnInit() {
  		this.memberservice
      		.getMembers()
      		.subscribe((data: User[]) => {
        		this.members = data;
        });
    }
}

Run this project http://localhost:4200/index.

Step 11: Angular 6 Edit and Update the Data.

edit.component.html

<div class="card">
    <div class="card-body">
      <form [formGroup]="memberFrm" novalidate>
        <div class="form-group">
          <label class="col-md-4">Member Name</label>
          <input type="text" class="form-control" formControlName="name" #name [(ngModel)] = "member.name"/>
        </div>
        <div *ngIf="memberFrm.controls['name'].invalid && (memberFrm.controls['name'].dirty || memberFrm.controls['name'].touched)" class="alert alert-danger">
          <div *ngIf="memberFrm.controls['name'].errors.required">
            Name is required.
          </div>
        </div>
        <div class="form-group">
          <label class="col-md-4">Member Age</label>
          <input type="text" class="form-control" formControlName="age" #age [(ngModel)] = "member.age"/>
        </div>
        <div *ngIf="memberFrm.controls['age'].invalid && (memberFrm.controls['age'].dirty || memberFrm.controls['age'].touched)" class="alert alert-danger">
          <div *ngIf="memberFrm.controls['age'].errors.required">
            Age is required.
          </div>
        </div>
          <div class="form-group">
            <button (click)="updateMember(name.value, age.value)" [disabled]="memberFrm.pristine || memberFrm.invalid" class="btn btn-success">Add</button>
          </div>
      </form>
    </div>
  </div>

Inside edit.component.ts

// edit.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { MemberService } from '../../member.service';
import { Member } from '../index/Member';

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

    member: any = {};
    memberFrm: FormGroup;
    constructor(private route: ActivatedRoute, 
                private router: Router, 
                private service: MemberService, 
                private fb: FormBuilder) { 
        this.createForm();
    }

    createForm() {
    this.memberFrm = this.fb.group({
         	name: ['', Validators.required ],
          	age: ['', Validators.required ]
   		});
  	}

    ngOnInit() {
        this.route.params.subscribe(params => {
     		this.service.editMember(params['id']).subscribe(response => {
        		this.member = response;
      	});
    });
  }
}

edit.component.ts

// edit.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { MemberService } from '../../member.service';
import { Member } from '../index/Member';

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

    member: any = {};
    memberFrm: FormGroup;
    constructor(private route: ActivatedRoute, 
                private router: Router, 
                private service: MemberService, 
                private fb: FormBuilder) { 
        this.createForm();
    }

    createForm() {
    this.memberFrm = this.fb.group({
         	name: ['', Validators.required ],
          	age: ['', Validators.required ]
   		});
  	}

    ngOnInit() {
        this.route.params.subscribe(params => {
     		this.service.editMember(params['id']).subscribe(response => {
        		this.member = response;
      	});
    });
  }
}

member.service.ts

// member.service.ts

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

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

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

 	constructor(private http: HttpClient) { }

  	addMember(name, age) {
        const obj = {
          name: name,
          age: age
        };
        this
        	.http
        	.post(`${this.uri}/add`, obj)
            .subscribe(response => 
            	console.log('Done')
            );
  	}

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

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

member.service.ts

Read Also:  PHP Parse URL Querystring Into Array

After, update All the data content. then simple the following source code inside member.service.ts file. O will write step by step the update angular 6 function inside member.service.ts file.

// member.service.ts

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

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

  uri: String = 'http://localhost:4000/members';

  constructor(private http: HttpClient) { }

  addMember(name, age) {
        const obj = {
          name: name,
          age: age
        };
        this
        	.http
        	.post(`${this.uri}/add`, obj)
            .subscribe(response => 
            	console.log('Done')
            );
  	}

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

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

   updateMember(name, age, id) {

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

edit.component.ts

After that, simple the following source code inside edit.component.ts main file.

// edit.component.ts

updateMember(name, age) {
     this.route.params.subscribe(params => {
     this.service.updateMember(name, age, params['id']);
     this.router.navigate(['index']);
  });
}

index.component.html

Lets start, We are source coding the All the main simple index.component.html file.

<tbody>
      <tr *ngFor="let member of members">
          <td>{{ member.name }}</td>
          <td>{{ member.age }}</td>
          <td><a [routerLink]="['/edit', member._id]" class="btn btn-success">Edit</a></td>
          <td><button (click)="deleteMember(member._id)"  class="btn btn-danger">Delete</button></td>
      </tr>
</tbody>

index.component.ts

And then, write the deleteMember function inside main root Angular 6 index.component.ts file.

// index.component.ts

import { Component, OnInit } from '@angular/core';
import { Member } from './Member';
import { MemberService } from '../../member.service';

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

    members: Member[];

    constructor(private memberservice: MemberService) { }

    ngOnInit() {
  	this.memberservice
      	    .getMembers()
      	    .subscribe((data: Member[]) => {
        	this.members = data;
        });
   }

   deleteMember(id) {
     this.memberservice.deleteMember(id).subscribe(response => {
      console.log('Deleted');
    });
   }
}

Lastly, simple the deleteMember function inside member.service.ts file.

member.service.ts

// member.service.ts

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

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

    uri: String = 'http://localhost:4000/members';

 	constructor(private http: HttpClient) { }

  	addMember(name, age) {
        const obj = {
          name: name,
          age: age
        };
        this
        	.http
        	.post(`${this.uri}/add`, obj)
            .subscribe(response => 
            	console.log('Done')
            );
  	}

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

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

 	updateMember(name, age, id) {

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

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

If you have any stuck or problems in Angular 6 CRUD Insert Update delete operations, then you freely ask in a this comment below.

Angular 6 CRUD Example Tutorial
Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Angular 6 CRUD Example Tutorial From Scratch.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  How to fix Class 'App\Http\Controllers\Auth' not found
  2. Read Also:  Clear All Cache From Laravel project 5.7
  3. Read Also:  Call Function in ng-click Event using Angular Example
  4. Read Also:  jQuery Ajax CRUD operations in Laravel 5.7
  5. Read Also:  Angular 6 CRUD Tutorial Example From Scratch
  6. Read Also:  Ajax Image Upload without Refreshing Page using Jquery
  7. Read Also:  Angular 6 AJAX Tutorial Example From Scratch
  8. Read Also:  laravel get all query string
  9. Read Also:  How to Get Current Date & Time in Python
  10. Read Also:  angular 6 crud example - crud operation in angular 6

Leave a Comment

Your email address will not be published. Required fields are marked *