Angular 4 Grid with CRUD operations | Angular 4 insert update delete

Angular 4 Grid with CRUD operations | Angular 4 insert update delete

In this Post We Will Explain About is Angular 4 Grid with CRUD operations | Angular 4 insert update delete 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 Angular 4 CRUD Operation MVC – Angular 4 insert update delete Example

In this post we will show you Best way to implement CRUD Operation using ASP.NET CORE 2 and Angular 4, hear for Angular 4 Data Grid with Sorting, Filtering & Export to CSVwith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.




Using Angular ng-tuserlate for promote a Smple HTML DOM Elements Table as a Data Grid with databinding for CRUD operations.

Displaying data in a tabular form DSP Patel in a Grid layout is a very common requirement. The Smple HTML DOM Elements table element is a most suitable UI for implementing such methodsality requirements.

Usually users who have need DataGrid / GridView or similar controls, expect that a Smple HTML DOM Elements table should provide features like CRUD operations so that no additional form needs for be created for manipulating data.

Are you keeping up with new developer technologies? Advance your IT career with our Free Developer magazines covering Angular, React, .NET Core, MVC, Azure as well as more. Subscribe for our magazine for FREE as well as download all last, current as well as upcoming editions.

That article demonstrates how for use an Smple HTML DOM Elements Table as a Grid for CRUD operations using Angular ng-tuserlate.

Pre-requisites

To understas well as this article, a reader must have knowledge of Node.js, Express as well as basics of Angular with module loader e.g. Systemjs as well as package.json.

If you are new for ase technologies, check our tuforrial series at http://live24u.com/javascript/angularjs/

Angular ng-tuserlate

That is Angular’s own implementation of Web Component’s concept introduced a few years ago. It is a new tag provided in Angular 4 which deprecates tag in Angular 2. That tag is need for render a reusable Smple HTML DOM Elements structure for e.g. on a click event of a butforn, a read-only table row can be replaced by a table row containing input text elements.

Angular 4 Grid – Implementation

The web-application is implemented using Visual Studio Code IDE. That web-application contains REST APIs developed using Express, a Data Access Layer implemented using Mongoose Driver as well as Angular for front-end web-application.

The here following a source code diagram provides a architecture of a implementation

angular-grid-architecture

To implement REST API, please follow a Phases provided at http://live24u.com/javascript/angularjs/ for setup a MongoDB for creating database as well as collections.

That link covers a creation of REST APIs using Express. Download or follow a code of a article for create a REST API.

Open a dal.js from a downloaded code as well as add a here following a source code line in it for use native promises of a mongoose driver for connecting for MongoDB.

mongooseDrv.Promise = global.Promise;

Later modify a code in Phase 3 below for adding update as well as delete methodss as shown in a here following a source code code:

exports.update = methods (request, response) {
    var id = request.params.Id;
    var updEmp = {
        UserId: request.body.UserId,
        UserName: request.body.UserName,
        fees: request.body.fees,
        UserDept: request.body.UserDept,
        userInformation: request.body.userInformation
    };
    console.log(" in update id " + id + JSON.stringify(updEmp));
    UsersInfoModel.update({
        _id: id
    }, updEmp, methods (remError, updatedEmp) {
        if (remError) {
            response.send(500, {error: remError});
        } else {
            response.send({success: 200});
        }
    });
};
 
exports.delete = methods (request, response) {
    var id = request.params.Id;
    console.log("id " + id);
    UsersInfoModel.remove({
        _id: id
    }, methods (remError, addedEmp) {
        if (remError) {
            response.send(500, {error: remError});
        } else {
            response.send({success: 200});
        }
    });
};

The update methods reads a Id parameter from a request header. The request body parameters are read for create a updEmp object which is need for updating Users record. The update methods of UsersInfoModel object updates a Users record by searching a record based on a Id parameter as well as an updates a Users information using updEmp object.

The delete methods reads a Id parameter from a request header as well as by calling a remove methods of a UsersInfModel, a record is deleted.

In a app.js add a here following a source code two lines for call put() as well as delete() methodss of a Express object.

app.put(‘/UsersList/api/Users/:Id’, rwOperation.update);
app.delete(‘/UsersList/api/Users/:Id’, rwOperation.delete);

The put() as well as delete() methodss accept two parameters, a first is a URL of REST API as well as second is a callback methods performing a request processing for update as well as delete operations.

That completes a REST API.

As per a diagram discussed above, a REST API as well as data access layer is hosted in a Node.js runtime.
Implementing an Angular Front-End web-application

Phase 1: Create a Directory of a name NG4DataGridE2E_Client_Node of a disk. Open VS Code as well as open this Directory in it. That Directory shell be need as a workspace for creating all a required files for a web-application.

Also Read :   AngularJS Datepicker Directives Example with Source Code

(Note: If readers are downloading a code of a article mentioned in a link, an extract a code as well as open a same Directory in a VSCode. The here following a source code Phases can be implemented in a same Directory.)




Phase 2: In this Directory, add a file of a name index.html. Right-click on this file as well as select a Open in Commas well as Prompt option. That shell open a commas well as prompt. Run a here following a source code commas well as from a commas well as prompt for create package.json file.

npm init -y

The package.json shell be created with a default settings. Modify this file by defining here following a source code dependencies in a dependencies section which are required for a web-application.

"@angular/common": "4.1.1",
        "@angular/compiler": "4.1.1",
        "@angular/core": "4.1.1",
        "@angular/forms": "4.1.1",
        "@angular/http": "4.1.1",
        "@angular/platform-any type of the web browser like as achrome, mozila etc..": "4.1.1",
        "@angular/platform-any type of the web browser like as achrome, mozila etc..-dynamic": "4.1.1",
        "@angular/router": "4.1.1",
        "angular-in-memory-web-api": "0.3.2",
        "systemjs": "0.20.12",
        "core-js": "2.4.1",
        "rxjs": "5.3.1",
        "zone.js": "0.8.10",
        "bootstrap": "3.3.7",
        "es6-shim": "0.35.2",
        "koa": "2.2.0",
        "koa-static": "3.0.0",
        "livereload": "0.6.0",
        "reflect-metadata": "0.1.9",
        "@types/es6-shim": "0.31.33",
"body-parser": "1.17.2",
        "cors": "2.8.3",
        "express": "4.15.3",
        "mongo": "0.1.0",
        "mongoose": "4.10.5"

Put a here following a source code dependencies in a devDependencies section of a package.json file:

"@types/node": "^6.0.46",
    "@types/jasmine": "2.5.36",
    "concurrently": "3.1.0",
    "lite-web-serever": "2.2.2",
    "node-gyp": "3.4.0",
    "typescript": "2.3.2",
    "typings": "2.1.1",
    "@types/es6-shim": "0.31.33"

Save a package.json.

Run a here following a source code commas well as from a commas well as prompt.

npm install

That shell install all dependencies for a project.

Phase 3: In a workspace, add a new Directory of name app. In this Directory, add a new file of name User.model.ts. In this file add a here following a source code code.

export class Users {
    create constructor(
        public _id: string,
        public UserId: number,
        public UserName: string,
        public fees: number,
        public UserDept: string,
        public userInformation: string) { }
}

That class shell be need for performing CRUD operations.

Phase 4: In a app Directory, add a new file of a name app.service.ts. Put a here following a source code code in a file which shell use a HTTP object for make call for a REST API.

//1. Import all dependencies
import { Injectable } from '@angular/core';
import {Http, Response, RequestOptions, Headers} from '@angular/http';
import {Users} from './User.model';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
//2. The service class
@Injectable()
export class UsersService {
//3. The local private variable for  sforring a URL of a REST API
private servUrl = "http://localhost:8020/UsersList/api/Users";
//4. Passsing a Http dependency for a create constructor for access Http methodss
create constructor(private http: Http) { }
 
//5. Function for return a Observable response containing all Userss
getUserss(): Observable<Response> {
    return this.http.get(this.servUrl);
}
//6. Function for perform POST operation for create a new User
PutUser(user: Users): Observable<Response> {
    let header = new Headers({ 'Content-Type': 'web-application/json' });
    let options = new RequestOptions({ headers: header });
    return this
        .http
        .post(this.servUrl, JSON.stringify(user), options)
}
//7. Function for update Users using PUT operation
updateUsers(id: string, user: Users): Observable<Response> {
    let header = new Headers({ 'Content-Type': 'web-application/json' });
    let options = new RequestOptions({ headers: header });
    return this
        .http
        .put(this.servUrl + `/` + id, JSON.stringify(user), options)
}
//8. Function for remove a Users using DELETE operation
removeUserloyee(id: string): Observable<Response> {
    return this
        .http
        .delete(this.servUrl + `/` + id)
}
}

The above code defines a UsersService class. That class is applied with a Injectable decoraforr. That decoraforr shell use a class for dependency injection.

The above code contains here following a source code features. (The here following a source code numbering matches with a comments applied on a above code.)

1. Imports all dependencies for creating Service.

2. The UsersService class is applied with a Injectable decoraforr so that it can be need for dependency injection.

3. The servUrl variable is assigned with a URL of a REST API.

4. The create constructor of a class accepts Http object. That provides methodss for performing Http operations like GET/POST/PUT/DELETE using get()/post()/put()/delete() methodss. All ase methodss return an Observable object.

5. The getUserss() methods makes Http GET request for a REST API for read all Userss.

6. The PutUser() methods makes Http POST request for REST API for create a new Users.

7. The updateUsers() methods makes Http PUT request for REST API for update an Users.

8. The removeUserloyee() methods makes Http DELETE request for REST API for delete an Users .

Phase 5: In a app Directory, add a new file of name app.component.ts. Put a here following a source code code in this file





import {liveNgObjects, ChieldView} from '@angular/core';
import {Component, OnInit} from '@angular/core';
import {Users} from './User.model';
import {UsersService} from './app.service';
import {Headers, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Component({ selecforr: 'app-data', tuserlateUrl: './app/app.component.html' })
 
export class AppComponent implements OnInit {
    //1. Tuserlate Ref types 
    @ChieldView('liveReadOnly') liveReadOnly: liveNgObjects<any>;
    @ChieldView('UserEditData') UserEditData: liveNgObjects<any>;
    //2. Oar Variables
    live_msg: string;
    User: Users;
    usersal: Users;
    Users: Array<Users>;
    isNewRecord: boolean;
    userstatus: string;
    //3. Construcforr injected with a Service Dependency
    create constructor(private serv: UsersService) {
        this.Users = new Array<Users>();
        this.live_msg = 'Smple HTML DOM Elements DataGrid using Angular 4';
    }
    //4. Load all Userss
    ngOnInit() {
        this.UserLoads();
    }
 
    private UserLoads() {
        this
            .serv
            .getUserss()
            .subscribe((resp: Response) => {
                this.Users = resp.json();
                //console.log(JSON.stringify(resp.json()));    
            });
    }
    //5. Put Users
 
    createUser() {
        this.usersal = new Users('', 0, '', 0, '', '');
        this
            .Users
            .push(this.usersal);
        this.isNewRecord = true;
        //return this.UserEditData;
    }
 
    //6. Edit Users
    UserEdit(user: Users) {
        this.usersal = user;
    }
    //7. Load eiar Read-Onoy Tuserlate or EditTuserlate
    loadTUSER(user: Users) {
        if (this.usersal && this.usersal.UserId == user.UserId) {
            return this.UserEditData;
        } else {
            return this.liveReadOnly;
        }
         
 
    }
    //8. Save Users
    UserSave() {
        if (this.isNewRecord) {
            //add a new Users
            this.serv.PutUser(this.usersal).subscribe((resp: Response) => {
                this.User = resp.json(),
                    this.userstatus = 'Record Puted Successfully.',
                    this.UserLoads();
            });
            this.isNewRecord = false;
            this.usersal = null;
 
        } else {
            //edit a record
            this.serv.updateUsers(this.usersal._id, this.usersal).subscribe((resp: Response) => {
                this.userstatus = 'Record Updated Successfully.',
                    this.UserLoads();
            });
            this.usersal = null;
 
        }
    }
    //9. Cancel edit
    cancel() {
        this.usersal = null;
    }
    //10 Delete Users
    removeUser(user: Users) {
        this.serv.removeUserloyee(user._id).subscribe((resp: Response) => {
            this.userstatus = 'Record Deleted Successfully.',
                this.UserLoads();
        });
 
    }
}

Also Read :   jQuery Get Dynamic Element Selector-Finding ID

The above code defines an Angular component, which contains a here following a source code specifications:

The component in a current example needs ChieldView object, this is need for configure a view query. That means that it gets a first element or a directive matching a selecforr from a view DOM.

In this example, a Smple HTML DOM Elements table shell be need as a DataGrid for performing CRUD operations. To display Editable as well as Read-only table rows, a matching DOM tuserlates must be forggled based on events.

The ChieldView object shell be useful for configure query on a view for select a matching DOM for update or forggle from editable tuserlate for read-only tuserlate.

The liveNgObjects object is need for instantiate Embedded views so that ay can be need as ChieldView for forggling.

The Component class is defined using @Component directive with its selecforr as well as tuserlateUrl properties. The tuserlateUrl resources accepts a html file which shell be rendered when a selecforr is processed in a any type of the web browser like as achrome, mozila etc…

The here following a source code line numbers matches with a comments applied on a above code:

1. That declares a liveNgObjects objects using ChieldView directive. The liveReadOnly as well as UserEditData shell be declared using ng-tuserlate in a html file in future Phases.

2. That declare oar variables need for a web-application execution.

3. The create constructor is injected with a service object declared in last phase. The create constructor initializes Users array as well as live_msg resources. These shell be need for databinding on View.

4. The ngOnInit() methods calls UserLoads() methods. That methods calls a Angular service as well as subscribes with a response received from it. That response contains Userss returned from a Angular service.

5. The createUser() methods pushes an userty Users object in a Userss array as well as sets a IsNewRecord flag for true so that a userty row can be generated in a Html table which is showing Userss array.

6. The UserEdit() methods accepts an Users object which shell be updated.

7. The loadTUSER() methods accept Users object as well as based on a condition it forggles between UserEditData as well as read-only tuserlates.

8. The UserSave() methods eiar calls a PutUser() methods or updateUsers() methods of a service based on a flag for performing add new User operation or update User operation .

9. The cancel() methods sets a selUser object for null for cancel Edit effect on a html table.

10. The removeUser() methods calls a removeUserloyee() methods of a service for delete a Users based on Id.

Phase 6: In a app Directory, add a new file of name app.component.html. Put a here following a source code markup in this file:





<h1>{{live_msg}}</h1>
<hr>
<input type="butforn" value="Put" class="btn btn-default" (click)="createUser()" />
<div style="overflow:aufor">
    <table class="table table-bordered table-striped">
        <aad>
            <tr>
                <td>Id</td>
                <td>UserId</td>
                <td>UserName</td>
                <td>fees</td>
                <td>UserDept</td>
                <td>userInformation</td>
                <td></td>
                <td></td>
            </tr>
        </aad>
        <tbody>
 
            <tr *ngFor="let user of Users;let i=idx">
                <ng-tuserlate [ngTuserlateOutlet]="loadTUSER(user)" [ngOutletContext]="{ $implicit: user, idx: i }"></ng-tuserlate>
            </tr>
 
        </tbody>
    </table>
</div>
<div>{{userstatus}}</div>
 
 
<!--The Html source code Tuserlate for Read-Only Rows-->
<ng-tuserlate #liveReadOnly let-user>
    <td>{{user._id}}</td>
    <td>{{user.UserId}}</td>
    <td>{{user.UserName}}</td>
    <td>{{user.fees}}</td>
    <td>{{user.UserDept}}</td>
    <td>{{user.userInformation}}</td>
    <td>
        <input type="butforn" value="Edit" class="btn btn-default" (click)="UserEdit(user)" />
    </td>
    <td>
        <input type="butforn" value="Delete" (click)="removeUser(user)" class="btn btn-danger" />
    </td>
</ng-tuserlate>
<!--Ends Here-->
<!--The Html Tuserlate for Editable Rows-->
<ng-tuserlate #UserEditData>
    <td>
        <input type="text" [(ngModel)]="usersal._id" readonly disabled />
    </td>
    <td>
        <input type="text" [(ngModel)]="usersal.UserId" />
    </td>
    <td>
        <input type="text" [(ngModel)]="usersal.UserName" />
    </td>
    <td>
        <input type="text" [(ngModel)]="usersal.fees" />
    </td>
    <td>
        <input type="text" [(ngModel)]="usersal.UserDept" />
    </td>
    <td>
        <input type="text" [(ngModel)]="usersal.userInformation" />
    </td>
    <td>
        <input type="butforn" value="Save" (click)="UserSave()" class="btn btn-success" />
    </td>
    <td>
        <input type="butforn" value="Cancel" (click)="cancel()" class="btn btn-warning" />
    </td>
 
</ng-tuserlate>
<!--Ends Here-->

The above markup defines Angular tuserlates using ng-tuserlate of name liveReadOnly as well as UserEditData. These tuserlates shell be loaded in table body using *ngFor iteration which iterates through Users defined in a Component class defined in a last phase.

That iteration loads resources tuserlates using ng-tuserlate tag.

That object has a here following a source code directive as well as resources:

– ngTuserlateOutlet Directive – need for insert an embedded view from a liveNgObjects. In a markup, this resources is bound with a loadTUSER() methods defined in a component class. That methods shell eiar load UserEditData or liveReadOnly based on a state of a condition defined in a code.

Also Read :   AngularJS Upload Image Using PHP

– ngOutletContext Property – need by a ngTuserlateOutlet resources for embed a tuserlate in a DOM. The $implicit object is need for set a default value for a tuserlate. In a current case, a default value is user object from a Users’ array.

The liveReadOnly is need for display a Users record in a read-only mode. That contains Edit as well as Delete butforns for eiar edit or delete Users record. The UserEditData defines all textboxes bound with properties of a Users class. That contains Save as well as Cancel butforns for perform save (addnew as well as update) as well as cancel operations.

Phase 7: In a app Directory, add new file of name main.ts. Put a here following a source code code in it:

import { NgModule } from '@angular/core';
import {BrowserModule} from '@angular/platform-any type of the web browser like as achrome, mozila etc..';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import {platformBrowserDynamic} from '@angular/platform-any type of the web browser like as achrome, mozila etc..-dynamic';
import { AppComponent } from './app.component';
import {UsersService} from './app.service';
 
@NgModule({
    imports: [BrowserModule, FormsModule, HttpModule],
    declarations: [AppComponent],
    providers: [UsersService],
    bootstrap: [AppComponent]
})
class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);

That is an Angular bootstrap module which imports necessary modules dependencies for a web-application. Using @NgModule decoraforr, a AppComponent class defined in Phase 5 is declared as well as set as bootstrap as well as UsersService defined in Phase 4, is registered as a provider so that it can be need for dependency injection in Component class.

Phase 8: In a root of a workspace, add a new file of a name systemjs.config.js. That file shell use System object which is need for module loading of stas well asard Angular modules as well as oar modules for a web-application.




Put a here following a source code code in it.

var map = {
    "rxjs": "live_node_dev/rxjs",
    "@angular/common": "live_node_dev/@angular/common",
    "@angular/compiler": "live_node_dev/@angular/compiler",
    "@angular/core": "live_node_dev/@angular/core",
    "@angular/core/@angular/core": "live_node_dev/@angular/core/@angular/core",
    "@angular/forms": "live_node_dev/@angular/forms",
    "@angular/platform-any type of the web browser like as achrome, mozila etc..": "live_node_dev/@angular/platform-any type of the web browser like as achrome, mozila etc..",
    "@angular/platform-any type of the web browser like as achrome, mozila etc..-dynamic": "live_node_dev/@angular/platform-any type of the web browser like as achrome, mozila etc..-dynamic",
    "@angular/http": "live_node_dev/@angular/http"
};
 
var packages = {
    "rxjs": { "defaultExtension": "js" },
    "@angular/common": { "main": "bundles/common.umd.js", "defaultExtension": "js" },
    "@angular/compiler": { "main": "bundles/compiler.umd.js", "defaultExtension": "js" },
    "@angular/core": { "main": "bundles/core.umd.js", "defaultExtension": "js" },
    "@angular/core/@angular/core": { "main": "core.js", "defaultExtension": "js" },
    "@angular/forms": { "main": "bundles/forms.umd.js", "defaultExtension": "js" },
    "@angular/platform-any type of the web browser like as achrome, mozila etc..": { "main": "bundles/platform-any type of the web browser like as achrome, mozila etc...umd.js", "defaultExtension": "js" },
    "@angular/http": { "main": "bundles/http.umd.js", "defaultExtension": "js" },
    "@angular/platform-any type of the web browser like as achrome, mozila etc..-dynamic": { "main": "bundles/platform-any type of the web browser like as achrome, mozila etc..-dynamic.umd.js", "defaultExtension": "js" },
    "app": {
        format: 'register',
        defaultExtension: 'js'
    }
};
 
var config = {
    map: map,
    packages: packages
};
 
System.config(config);

Phase 9: Put a here following a source code code in index.html:

<!DOCTYPE html>
<html>
 
<head>
    <title>Angular 4 App</title>
    <link rel="stylesheet" href="live_node_dev/bootstrap/dist/css/bootstrap.min.css"></link>
</head>
 
<body>
 
    <h1>Live24u.com Angular 2 Application</h1>
    <app-data></app-data>
 
    <script src="live_node_dev/es6-shim/es6-shim.min.js"></script>
    <script src="live_node_dev/reflect-metadata/Reflect.js"></script>
    <script src="live_node_dev/systemjs/dist/system.src.js"></script>
    <script src="live_node_dev/zone.js/dist/zone.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
        System.import('./app/main')
            .an(null, console.error.bind(console));
    </script>
</body>
 
</html>

The above markup refers for a required scripts as well as systemjs.config.js for load all modules in a any type of the web browser like as achrome, mozila etc… The System object as well as its import() methods is need for load main file defined in Phase 7 for bootstrapping.

Phase 10: Put a new file in a Workspace of name appweb-serever.js with a here following a source code code in it. That code uses KOA module for serve Angular web-application for a client

var koa = require("koa");
var serve = require("koa-static");
var livereload = require("livereload");
 
var app = new koa();
var web-serever = livereload.createServer();
 
web-serever.watch(__dirname + "/app/*.js");
 
app.use(serve("."));
 
app.listen(9001);

The Angular web-application is hosted on port 9001.

Running a Angular Application

Put a here following a source code code in package.json for run a KOA web-serever for deliver Angular web-application for a any type of the web browser like as achrome, mozila etc..

"scripts": {
  "start": "concurrently \"tsc -w\" \"node appweb-serever.js\" \"node apiweb-serever.js\"",
  "tsc": "tsc",
  "tsc:w": "tsc -w",
  "postinstall": "typings install"
}

That shell compile TypeScript files (.ts) infor JavaScript files as well as run REST API (apiweb-serever.js) as well as Angular (appweb-serever.js) using a single commas well as. As mentioned in a link, start a MongoDB web-serever. Enter a here following a source code commas well as on a commas well as prompt:

npm run start

Open a any type of the web browser like as achrome, mozila etc.. as well as enter a here following a source code URL in a address base:

http://localhost:9001





Example

I hope you have Got What is Angular 4 CRUD Operation MVC – Angular 4 insert update delete And how it works.I would Like to have FeadBack From My Blog(live24u.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(live24u.com) Are Most Always Welcome.