Angular 5 CRUD insert update delete Tutorial Part 2

Angular 5 CRUD insert update delete Tutorial Part 2

In this Post We Will Explain About is Angular 5 CRUD insert update delete Tutorial Part 2 With Example and Demo.Welcome on Live24u.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to insert update delete using Angular 5 Example

In this post we will show you Best way to implement insert update delete in asp.net using Angular 5, hear for Angular 5 Grid with CRUD operations with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.




Angular 5 CRUD Tutorial Example From Scratch

In Our previous posts We have explained Step By Step Angular 5 CRUD Operation various topics like

Phase 10: Configure Node.js MongoDB backend.

And then, I require to install the step by step express main framework and other more cmd to dependencies via NPM

npm install --save express body-parser cors mongoose nodemon

Switch to newly made file server.js file and some enter the following below source code into it.

// server.js

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

make one data config folder inside our nodejs and angular 5 project root. In that make one simple file called DB.js.

// DB.js

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

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

Phase 11: Create Express routes for our application.

In models directory, make one model called Student.js.

Also Read :   AngularJS insert in php MYSQL

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

// Define collection and schema for Items
var Student = new Schema({
  name: {
    type: String
  },
  fees: {
    type: Number
  }
},{
    collection: 'students'
});

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

In the expressRouter directory, make one file called coinRoutes.js.

// coinRoutes.js

var express = require('express');
var app = express();
var coinRoutes = express.Router();

// Require Item model in our routes module
var Student = require('../models/Student');

// Defined store route
coinRoutes.route('/add').post(function (req, data_results) {
  var student = new Student(req.body);
   student.save()
    .then(item => {
    data_results.status(200).json({'student': 'Student added successfully'});
    })
    .catch(err => {
    data_results.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
coinRoutes.route('/').get(function (req, data_results) {
   Student.find(function (err, students){
    if(err){
      console.log(err);
    }
    else {
      data_results.json(students);
    }
  });
});

// Defined edit route
coinRoutes.route('/edit/:id').get(function (req, data_results) {
  var id = req.params.id;
  Student.findById(id, function (err, student){
      data_results.json(student);
  });
});

//  Defined update route
coinRoutes.route('/update/:id').post(function (req, data_results) {
   Student.findById(req.params.id, function(err, student) {
    if (!student)
      return next(new Error('Could not load Document'));
    else {
      student.name = req.body.name;
      student.fees = req.body.fees;

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

// Defined delete | remove | destroy route
coinRoutes.route('/delete/:id').get(function (req, data_results) {
   Student.findByIdAndRemove({_id: req.params.id}, function(err, student){
        if(err) data_results.json(err);
        else data_results.json('Successfully removed');
    });
});

module.exports = coinRoutes;

This file will be included below some source code in our server.js file.

// server.js

coinRoutes = require('./expressRoutes/coinRoutes');

app.use('/students', coinRoutes);

Phase 12: Insert the value in the MongoDB.

simple From the client browser front end side, I required to set up HttpClientModule as well fire up the HTTP ajax call Post call to the NodeJS server.

// server.js

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

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;

app.use('/students', coinRoutes);

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

I required to some include the ReactiveFormsModule in the app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { IndexComponent } from './components/index/index.component';
import { CreateComponent } from './components/create/create.component';
import { EditComponent } from './components/edit/edit.component';
import { appRoutes } from './routerConfig';

import { StudentService } from './student.service';

@NgModule({
  declarations: [
    AppComponent,
    IndexComponent,
    CreateComponent,
    EditComponent
  ],
  imports: [
    BrowserModule, RouterModule.forRoot(appRoutes), HttpClientModule, ReactiveFormsModule
  ],
  providers: [StudentService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, I am HTML form validating. So first below source code the form HTML in the create.component.html.

Also Read :   Angular 5 CRUD insert update delete Tutorial Part 1

<div class="live24u panel panel-success">
    <div class="live24u panel-heading">
      {{ title }}
    </div>
    <div class="live24u panel-body">
      <form [formGroup]="liveFrm" novalidate>
        <div class="stud form-group live24u">
          <label class="col-md-4">Student Name</label>
          <input type="text" class="liveFrm form-control lst" formControlName="name" #name />
        </div>
        <div *ngIf="liveFrm.controls['name'].invalid && (liveFrm.controls['name'].dirty || liveFrm.controls['name'].touched)" class="alert alert-danger">
          <div *ngIf="liveFrm.controls['name'].errors.required">
            Name is required.
          </div>
        </div>
        <div class="stud form-group live24u">
          <label class="col-md-4">Student Fees</label>
          <input type="text" class="liveFrm form-control lst" formControlName="fees" #fees/>
        </div>
        <div *ngIf="liveFrm.controls['fees'].invalid && (liveFrm.controls['fees'].dirty || liveFrm.controls['fees'].touched)" class="alert alert-danger">
          <div *ngIf="liveFrm.controls['fees'].errors.required">
            Fees is required.
          </div>
        </div>
          <div class="stud form-group live24u">
            <button (click)="addStudents(name.value, fees.value)" [disabled]="liveFrm.pristine || liveFrm.invalid" class="btn btn-success">Add</button>
          </div>
      </form>
    </div>
  </div>

and then, we required to below source code the logic of HTML form validation in the create.component.ts file.

// create.component.ts

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

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

  title = 'Add Student';
  liveFrm: FormGroup;
  constructor(private coinservice: StudentService, private fb: FormBuilder) {
    this.makeForm();
   }
  makeForm() {
    this.liveFrm = this.fb.group({
      name: ['', Validators.required ],
      fees: ['', Validators.required ]
   });
  }
  addStudents(name, fees) {
      this.coinservice.addStudents(name, fees);
  }
  ngOnInit() {
  }
}

Below the source code the student.service.ts file to data insert the data into the mysql database.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Injectable()
export class StudentService {

  constructor(private http: HttpClient) { }

  addStudents(name, fees) {
    const live_url = 'http://YOUR_SERVER_PORT/students/add';
    const my_object = {
      name: name,
      fees: fees
    };
    this.http.post(live_url, my_object)
        .subscribe(data_results => console.log('Good Luck Done!'));
  }
}

Phase 13: Display the data to the frontend.

In the index.component.html main file, below the following source code.

Also Read :   Difference between internal and external jQuery | javascript

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

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

After, you required to HTML data update the main index.component.ts below source code file and call the angular 5 service functions to create an http ajax call get request.

import { StudentService } from './../../student.service';
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

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

  students: any;

  constructor(private http: HttpClient, private service: StudentService) {}

  ngOnInit() {
    this.getStudents();
  }

  getStudents() {
    this.service.getStudents().subscribe(data_results => {
      this.students = data_results;
    });
  }
}

Below source code the student.service.ts file to create an http methods of get request.

import { Injectable } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class StudentService {

  result: any;
  constructor(private http: HttpClient) {}

  addStudents(name, fees) {
    const live_url = 'http://YOUR_SERVER_PORT/students/add';
    const my_object = {
      name: name,
      fees: fees
    };
    this
      .http
      .post(live_url, my_object)
      .subscribe(data_results =>
          console.log('Good Luck Done!'));
  }

  getStudents() {
    const live_url = 'http://YOUR_SERVER_PORT/students';
    return this
            .http
            .get(live_url)
            .map(data_results => {
              return data_results;
            });
  }

  editStudent(id) {
    const live_url = 'http://YOUR_SERVER_PORT/students/edit/' + id;
    return this
            .http
            .get(live_url)
            .map(data_results => {
              return data_results;
            });
  }
}

Angular 5 CRUD Tutorial Example From Scratch

In Our previous posts We have explained Step By Step Angular 5 CRUD Operation various topics like

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example





Example

I hope you have Got What is Angular 5 CRUD Operation Using Node, Express, MongoDB And how it works.I would Like to have FeedBack From My Blog(live24u.com) readers.Your Valuable FeedBack,Any Question,or any Comments about This Article(live24u.com) Are Most Always Welcome.