Introduction:
In this post, explained a example on the Angular 2 CRUD(Create, Read, Update and Delete) opearations using PhP.
Following prerequisites are required.
1. Angular 2 Basis setup
2. MAMP Server(WAMP for windows) to run PhP code.

In this example, we will read list of records from JSON file and then show it in a table. User can search,edit or delete the records. User also can create new record. Create two directories inside angular 2
app folder named
Dashboard and
User .
Create a interface to define user records properties like below and export it.
User/user.ts:
|
export interface User { id:number; name:string; phoneno:string; email:string; } |
Keep the following files on MAMP server and run the server.
htdocs/www/userData.json:
|
//Mock data [ {"id":1,"name":"missi","phoneno":"22222","email":"rama@gmail.com"}, {"id":2,"name":"devi","phoneno":"999999","email":"devi@gmail.com"}, {"id":3,"name":"naga","phoneno":"6666666","email":"nara@gmail.com"}, {"id":4,"name":"srvanthi","phoneno":"777777","email":"sravanthi@gmial.com"} ] |
htdocs/www/user.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
<?php header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); header('Access-Control-Allow-Methods: GET, POST, PUT'); ?> <?php function getUser() { $data = file_get_contents("userData.json"); $phpObj = json_decode($data, true); $jsonObj = json_encode($phpObj, true); echo $jsonObj; } function addUser() { $postdata = file_get_contents("php://input"); $phpObj = json_decode($postdata); $data = file_get_contents("userData.json"); $phpuserDetails = json_decode($data, true); array_push($phpuserDetails,$phpObj); file_put_contents('userData.json', json_encode($phpuserDetails)); echo json_encode($phpuserDetails); } function updateUser() { $postdata = file_get_contents("php://input"); $phpObj = json_decode($postdata, true); $data = file_get_contents("userData.json"); $phpuserDetails = json_decode($data, true); foreach($phpuserDetails as $key => $user){ if($user['id'] == $phpObj['id']){ $phpuserDetails[$key] = $phpObj; } } file_put_contents('userData.json', json_encode($phpuserDetails)); echo json_encode($phpuserDetails); } function deleteUser(){ $deleteId = $_GET["id"]; $data = file_get_contents("userData.json"); $phpuserDetails = json_decode($data, true); foreach($phpuserDetails as $key => $user){ if($user['id'] == $deleteId){ array_splice($phpuserDetails, $key, 1); } } file_put_contents('userData.json', json_encode($phpuserDetails)); echo json_encode($phpuserDetails); } /*getting action type from the url and calling respective function*/ $action = $_GET["action"]; if($action == "getUser"){ getUser(); }else if($action == "addUser") { addUser(); } else if($action == 'updateUser'){ updateUser(); } else { deleteUser(); } ?> |
Create a template and component for dashboard page is like below.
Dashboard/dashboard.component.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
<!--This section is to show message , when no records are found in backend--> <div class="panel panel-default" *ngIf="users.length == 0"> <div class="panel-heading"> <p>No User Details are available</p></div> <div class="panel-body" style="float:right"> <button class="btn btn-primary" (click)="isCreates=true">Create User</button> </div> </div> <!--This section is to show user records in the table, when the list of user records are exist--> <div class="panel panel-primary" *ngIf="users.length > 0"> <div class="panel-heading"> <h4 style="display:inline-block">Users List</h4> </div> <div class="panel-body"> <!--Added Serach box, to serach records from the table--> <div class="form-group"> <label for="search" class="col-sm-1 control-label">Search</label> <div class="col-sm-4"> <input type="search" class="form-control" name="search" [(ngModel)]="serachStr" (ngModelChange)="filterTable(serachStr)"> </div> </div> <table class="table table-striped"> <thead> <tr> <th>User Id</th> <th>Name</th> <th>Phone Number</th> <th>Email Id</th> <th>Action</th> </tr> </thead> <tbody> <tr *ngFor="let user of selectedUsers"> <td>{{834}}{{user.id}}</td> <td>{{user.name}}</td> <td>{{user.phoneno}}</td> <td>{{user.email}}</td> <td> <!--Added buttons to edit user and delete user--> <button class="btn btn-sm btn-danger" (click)="deleteUser(user.id)">delete</button> <button class="btn btn-sm btn-primary" (click)="isEdits=true;editUserData = user">Edit</button> </td> </tr> </tbody> </table> <button style="float:right" class="btn btn-success btn-primary" (click)="isCreates=true">Create New User</button> <button type="submit" class="btn btn-default" (click)="isCreates = false">Cancel</button> </div> </div> |
In the below dashboard component, we have injected the service named UserService and accessing respective service methods. We have added this
service to reduce the component logic.
Dashboard/dashboard.component.ts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
import { Component , OnInit} from '@angular/core'; import { Router } from '@angular/router'; import { User } from 'app/User/user'; import { UserService } from 'app/User/user.service'; @Component({ selector: 'dashboard', templateUrl: './dashboard.component.html', styleUrls: [ '../../../node_modules/bootstrap/dist/css/bootstrap.css' ], providers:[UserService] }) export class dashboardComponent implements OnInit{ users:User[] = []; selectedUsers:User[]=[]; returnIntems:User[]; isCreates:boolean = false; isEdits:boolean = false; /*Inject dependencies in constructor function as a input params*/ constructor(public router: Router, private userService : UserService) {} ngOnInit(){ /*getting user details on component intiation*/ this.userService ._getUser() .then(users => {this.users = users; this.selectedUsers = users}); } userAdded(users:User[]){ this.isCreates = false; this.isEdits = false; this.users = users; this.selectedUsers = users; } deleteUser(id){ /*Delete User handlear*/ this.userService ._deleteUser(id) .then(users => {this.users = users; this.selectedUsers = users}) } /*Search box handler*/ filterTable(input) { this.returnIntems = []; input.toLocaleLowerCase(); this.users.filter((tag) => { if(tag.name.toLocaleLowerCase().indexOf(input) >= 0 || tag.phoneno.toLocaleLowerCase().indexOf(input) >= 0 || tag.email.toLocaleLowerCase().indexOf(input) >= 0){ this.returnIntems.push(tag); } }); this.selectedUsers = this.returnIntems; } } |
Create a user service file and add methods to do CRUD operations by Http call.
User/user.service.ts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
User/user.service.ts: import { Injectable } from '@angular/core'; import { Http,Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; /*Importing user interface to define user class behaviour*/ import {User} from './user'; @Injectable() export class UserService { private headers = new Headers({ 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' }); constructor(private http: Http) {} _getUser(): Promise<User[]> { return this.http .get('http://localhost:8888/www/user.php?action=getUser') .toPromise() .then(this.handleSuccess) .catch(this.handleError); } _addUser(user:User):Promise<User[]> { console.log(user); return this.http .post('http://localhost:8888/www/user.php?action=addUser',user, {headers: this.headers}) .toPromise() .then(this.handleSuccess) .catch(this.handleError); } _deleteUser(id:number):Promise<User[]> { return this.http .post('http://localhost:8888/www/user.php?action=deleteUser&id='+id, {headers: this.headers}) .toPromise() .then(this.handleSuccess) .catch(this.handleError); } _editUser(user:User):Promise<User[]> { return this.http .post('http://localhost:8888/www/user.php?action=updateUser',user, {headers: this.headers}) .toPromise() .then(this.handleSuccess) .catch(this.handleError); } /*Http Ajax call success handler*/ private handleSuccess(data){ return data.json() as User[]; } /*Http Ajax call error handler*/ private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } } |
Create a template and component for create user and edit user like below.
User/createUser.component.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
<div class="col-sm-6 col-sm-6 col-sm-offset-3"> <form class="form-horizontal" novalidate #createUserForm="ngForm"> <div class="form-group"> <label for="id" class="col-sm-2 control-label">User id</label> <div class="col-sm-10"> <input type="text" class="form-control" name="id" [(ngModel)]="userObj.id" disabled> </div> </div> <div class="form-group"> <label for="name1" class="col-sm-2 control-label">User Name</label> <div class="col-sm-10"> <input type="text" class="form-control" name="name" placeholder="User Name" [(ngModel)]="userObj.name" #name1="ngModel" required> <div *ngIf="name1.errors && (name1.dirty || name1.touched)"> <span class="errorMsg" [hidden]="!name1.errors.required" style="color:red"> Name is required</span> </div> </div> </div> <div class="form-group"> <label for="number" class="col-sm-2 control-label">Phone No</label> <div class="col-sm-10"> <input type="text" class="form-control" name="number" placeholder="Phone no" [(ngModel)]="userObj.phoneno" #number="ngModel" required> <div *ngIf="number.errors && (number.dirty || number.touched)"> <span class="errorMsg" [hidden]="!number.errors.required" style="color:red">Mobile number is required</span> </div> </div> </div> <div class="form-group"> <label for="emailId" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="email" class="form-control" name="email" placeholder="Email" [(ngModel)]="userObj.email" #emailId="ngModel" required> <div *ngIf="emailId.errors && (emailId.dirty || emailId.touched)"> <span class="errorMsg" style="color:red" [hidden]="!emailId.errors.required">Email Id is required</span> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default" [disabled]="!createUserForm.form.valid" (click)="addUser()">Create User</button> </div> </div> </form> </div> |
User/createUser.component.ts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
import { Component,Input,Output,OnInit,EventEmitter } from '@angular/core'; import { UserService } from './user.service'; import { User } from './user'; @Component({ selector: 'create-user', templateUrl:'./createUser.component.html', styleUrls: [ '../../../node_modules/bootstrap/dist/css/bootstrap.css' ], providers:[UserService] }) export class CreateUserComponent implements OnInit{ private userObj:User; @Input() userData: User[]; /*Added event emitter for parent child component communication*/ @Output() userAdded = new EventEmitter<User[]>(); ngOnInit(){ this.userObj = <User>{ id: (this.userData.length+1) }; } constructor(private userService : UserService){} addUser() { this.userService ._addUser(this.userObj) .then(users => this.userAdded.emit(users)); } } |
User/editUser.component.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
<div class="col-sm-6 col-sm-6 col-sm-offset-3"> <form class="form-horizontal" novalidate #editUserForm="ngForm"> <div class="form-group"> <label for="id" class="col-sm-2 control-label">User id</label> <div class="col-sm-10"> <input type="text" class="form-control" name="id" [(ngModel)]="userObj.id" disabled> </div> </div> <div class="form-group"> <label for="name1" class="col-sm-2 control-label">User Name</label> <div class="col-sm-10"> <input type="text" class="form-control" name="name" placeholder="User Name" [(ngModel)]="userObj.name" #name1="ngModel" required> <div *ngIf="name1.errors && (name1.dirty || name1.touched)"> <span class="errorMsg" [hidden]="!name1.errors.required" style="color:red"> Name is required</span> </div> </div> </div> <div class="form-group"> <label for="number" class="col-sm-2 control-label">Phone No</label> <div class="col-sm-10"> <input type="text" class="form-control" name="number" placeholder="Phone no" [(ngModel)]="userObj.phoneno" #number="ngModel" required> <div *ngIf="number.errors && (number.dirty || number.touched)"> <span class="errorMsg" [hidden]="!number.errors.required" style="color:red">Mobile number is required</span> </div> </div> </div> <div class="form-group"> <label for="emailId" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="email" class="form-control" name="email" placeholder="Email" [(ngModel)]="userObj.email" #emailId="ngModel" required> <div *ngIf="emailId.errors && (emailId.dirty || emailId.touched)"> <span class="errorMsg" style="color:red" [hidden]="!emailId.errors.required">Email Id is required</span> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default" [disabled]="!editUserForm.form.valid" (click)="editUser()">Edit User</button> </div> </div> </form> </div> |
User/editUser.component.ts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
import { Component,Input,Output,OnInit,EventEmitter } from '@angular/core'; import { UserService } from './user.service'; import { User } from './user'; @Component({ selector: 'edit-user', templateUrl:'./editUser.component.html', styleUrls: [ '../../../node_modules/bootstrap/dist/css/bootstrap.css' ], providers:[UserService] }) export class EditUserComponent implements OnInit{ private userObj:User; @Input() editUserData: User; @Output() userUpdated = new EventEmitter<User[]>(); ngOnInit(){ this.userObj = this.editUserData; } constructor(private userService : UserService){} editUser() { this.userService ._editUser(this.userObj) .then(users => this.userUpdated.emit(users)); } } |
Add above created components to the dashboard page on condition based like below.
Updated Dashboard/dashboard.component.html:
|
<create-user *ngIf="isCreates" [userData]="users" (userAdded)="userAdded($event)"></create-user> <edit-user *ngIf="isEdits" [editUserData]="editUserData" (userUpdated)="userAdded($event)"></edit-user> |