Skip to main content
ag-grid-crud-example

ag-grid CRUD Example Using HTTP Rest Service In Angular 4/5

This tutorial explains about CRUD example using ag-grid and angular 4. This is the second part of Angular 4 Grid Pagination, Sorting and Searching Using ag-grid tutorial.

I am creating a table listing using HTTP restful service with pagination. I will also add sorting and searching into ag-grid using angular 4. You can integrate this code with angular 2, angular 4, and angular 5.

ag-grid-crud-example

I will integrate the following functionality into this ag-grid tutorial,

  • I will enable editing into ag-grid table listing.
  • Added ag-grid API to add, edit and delete records.
  • Added single and multiple row selection for deleting rows from listing.
  • I will add a new record into ag-grid listing.
  • I will delete the existing record from ag-grid table listing.

I am using the following files and folder,

  • package.json : This file used to add third-party libs. We will add ag-grid package information.
  • .angular-cli.json : This file is used to add ag-grid CSS and js files path here.
  • src/index.html : This file is used for HTML table container wrapper.
  • src/models/app.employee.ts : We will define the employee model interface.
  • src/app/app.module.ts : We will use this file to import ag-grid module.
  • src/app/app.component.ts : We will use it to define ag-grid table components and their configuration of them.
  • src/app/app.component.html : We will use to define ag-grid HTML view components here.

Let’s Integrate CRUD operation into Angular 4/5

I am assuming you have the existing code of my Ag-grid part 1 tutorial, I am extending that code and adding features to add new records using HTTP service and delete existing records from ag-grid.

Model in Angular 5

We will create a model interface to get employee-type data as JSON format into models/app.employee.ts file, This file will import into app.component.ts file:

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

export interface Employee {
      employee_name: string;
      employee_salary: number;
      employee_age: number;
    }

Enable Editing into ag-grid

We will enable edit ag-grid table functionality using the below code,

Added New, Update and Delete Button into ag-grid

We will add HTML code into the template file to display new records, update records and delete record button, I will add the below code into app.component.html file.

<div class="well">
<div><button class="btn btn-success" type="button"> Add New Row </button> <button class="btn btn-info" type="button"> Update Data </button> <button class="btn btn-danger" type="button"> Delete Selected </button></div>
</div>

As you can see, I have added onAddRow(), updateItems() and onRemoveSelected() method to handle add a new record, update record and delete record from ag-grid.

We will define the following ag grid option for row selection, grid API and update column API. I will add the below code into app.component.ts file:

title = 'AG-Grid Example Using Angular4';
  gridOptions: GridOptions;
  columnDefs: any[]
  rowData: any[];
  private rowSelection;
  private gridApi;
  private gridColumnApi;

Set Class level Variable For Edit and Select Row

this.gridOptions.defaultColDef = {
	editable: true
}
this.rowSelection = "multiple";
onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
}

We will add Forms Module into app.module.ts file.

import { FormsModule }   from '@angular/forms';
imports: [
	BrowserModule
]

How To Add New Record Into ag-grid

We will define onAddRow() method into app.component.ts file.

onAddRow() {
    var newItem = createNewRowData();
    var res = this.gridApi.updateRowData({ add: [newItem] });
    
    var data = {'name':res.add[0].data.employee_name, 'salary':res.add[0].data.employee_salary, 'age':res.add[0].data.employee_age};
    console.log(data)
    this.http.post('http://hostname/api/v1/create', data).subscribe(
        res => {
          console.log(res);
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log("Client-side error occured.");
        } else {
          console.log("Server-side error occured.");
        }
      });
  }

We have created sample object data using createNewRowData() and assigned to ag-grid using gridApi. We will create createNewRowData() method into app.component.ts file.

function createNewRowData() {
  var newData = {
    employee_name: "Adam "+newCount,
    employee_salary: 1111,
    employee_age: 35
  };
  newCount++;
  return newData;
}

How to Delete Record from ag-grid Using gridAPI

We have added onRemoveSelected() method with delete button, now we will define this method into app.component.ts file.

onRemoveSelected() {
    var selectedData = this.gridApi.getSelectedRows();
    var res = this.gridApi.updateRowData({ remove: selectedData });
    console.log(res.remove[0].data.id);
    var id = res.remove[0].data.id;
    this.http.delete('http://hostname/api/v1/delete/'+id).subscribe(
        res => {
          console.log(res);
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log("Client-side error occurred.");
        } else {
          console.log("Server-side error occurred.");
        }
      });
  }

6 thoughts to “ag-grid CRUD Example Using HTTP Rest Service In Angular 4/5”

Leave a Reply

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