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
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
Step 4: Insert Bootstrap CSS.
src >> index.html
app.component.html
Step 5: Create a HTML form in the make a component file.
create.component.html
Angular 6 CRUD Operations Demo
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.
// 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
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
Member Name | Member Age | Actions | |
{{ member.name }} | {{ member.age }} | Edit | Delete |
Member.ts
export interface Member { id: Number; name: String; age: Number; }
member.service.ts
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
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
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.
{{ member.name }} {{ member.age }} Edit
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.