Contact Me

Related Link

Angular CRUD example

If you are not working with Angular before please flow the instructions below. I hope you can doing a good starting with angular.

1. Create Angular App

  1. Open your terminal for Mac or CMD for Windows
  2. Go to the API folder (Type cd Desktop then cd API Folder Name)
  3. Type: npm install -g @angular/cli for install angular CLI globally.
  4. Type: ng new client For Create a new Angular project
  5. Create Angular App
  6. Got to the Angular project (Type cd client)
  7. Type ng serve --open for run your Angular project
  8. And see your first Angular App in your web browser.

    Angular App

    Please see the all command below togather for create your Angular App. Or click here quickstart for more details.

    npm install -g @angular/cli
    ng new client
    cd client
    ng serve --open
    

2. Bootstrap Install

  1. Go to your Angular project client folder
  2. Install Jquery, popper.js and bootstrap by this command below
  3. npm install jquery --save
    npm install popper.js --save
    npm install ngx-bootstrap bootstrap@4.1.1
    
  4. Opne angular.jsonfile from client the client folder
  5. Add the link into the styles array and scripts array like below
  6. Bootstrap Install
  7. go to your terminate stopped server press ctrl+c
  8. type ng serve to re start server and open in browser
  9. If everything is ok, then your app will be change and look like below

    Bootstrap Install

3. Add components and bootstrap tamplate

  1. Go to your Angular project: client > src > app folder
  2. Create a: components folder
  3. Add components and bootstrap tamplate
  4. Go to the components folder type: => cd src/app/components
  5. Create a Home components by the command into the components folder: => ng g component home
  6. home component
  7. Go to the src folder and open the index.html file
  8. Add the fontawesome link below into the index.html file
  9. <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous"> fontawesome link
  10. Open the home.component.html file and paste the simple template below
  11. <div class="jumbotron text-center"> <h1>MEAN Stack App CRUD Operations</h1> <p class="lead">Welcome to my MEAN Stack tutorial.</p> <div> <a class="btn btn-primary" (click)="addEmp($event)">Add Employ</a> </div> </div> <div class="row"> <div class="container"> <h3>Employ Data</h3> <table class="table table-bordered"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Emp Id</th> <th>Email</th> <th>Address</th> <th>Controll</th> </tr> </thead> <tbody> <tr> <td> 5b65716148d07207cb83b747</td> <td> Imran</td> <td> 0001</td> <td> imran@gmail.com</td> <td> Jakir hossain road, Mohammadpur, Dhaka-1207 </td> <td> <button class="btn btn-danger"><i class="far fa-trash-alt"></i></button> <button class="btn btn-primary"><i class="fas fa-pen"></i></button> </td> </tr> <tr> <td> 5b6bb9081d76550d344e40c1</td> <td> Shemul</td> <td> 0002</td> <td> shemul@gmail.com</td> <td> Kazi Nazrul Islam road, Mohammadpur, Dhaka-1207 </td> <td> <button class="btn btn-danger"><i class="far fa-trash-alt"></i></button> <button class="btn btn-primary"><i class="fas fa-pen"></i></button> </td> </tr> </tbody> </table> </div> </div>
  12. Open app.module.tsfile and import the RouterModule below
  13. import {RouterModule, Routes} from '@angular/router';
    
  14. Add the Routes path below above @NgModule
  15. const appRoutes:Routes = [
      {path: '', component: HomeComponent}
    ]
    
  16. Then imports the RouterModule into the imports array
  17. RouterModule.forRoot(appRoutes),
    

    Now app.module.tsfile look like below

    Router Module
  18. Add the router-outlet below into the app.component.html file
  19. <div class="container"> <router-outlet></router-outlet> </div>
  20. Finally go to your browser and see the output look like below
  21. bootstrap template

4. Angular CRUD operations

  1. Go to your Angular project: client > src > app folder
  2. Create a: services folder
  3. Angular CRUD operations
  4. Go to the services folder type: => cd src/app/services
  5. Create a new file called data by the command
  6. ng g service data
    
  7. Then go to the app.module.ts file and import the data.service.ts file. Please see the image below for more details
  8. Angular CRUD operations
  9. Create another one file in service folder called employ.service.ts and pest the code below.
  10. export class EmployService {
        public _id?:string;
        public name:string;
        public emp_Id: string;
        public email: string;
        public address:string;
    }
    
  11. Then import this file in app.module.ts file
  12. In the app.module.ts file import the HttpClientModule Module below and also define it in @NgModule imports array
  13. import { HttpClientModule }    from '@angular/common/http';
    
  14. Then go to the data.service.ts file and improt the module below
  15. import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Observable, of } from 'rxjs';
    import { catchError, map, tap } from 'rxjs/operators';
    
  16. Then inject the http servise in the constructor like below
  17. constructor(private http:HttpClient) { }
    
  18. Then add the function below for get data from the API
  19. getData(){
        let headers = new HttpHeaders();
        headers.append('Content-Type', 'application/json');
        const baseUri = 'http://localhost:2003/employ/read';
        return this.http.get(baseUri).pipe(map(result => result));
    }
    
  20. Now go to the home.component.ts file and import the data.service.ts and employ.service.ts file
  21. inject the DataService in constructor like below
  22.   constructor(
        private data:DataService,
      ) { }
    
  23. Now create a function in home.component.ts for get the DataService and return it in ngOnInit() function like below
  24. ngOnInit() {
    this.getEmpData()
    }
    
    private employService:EmployService[];
    getEmpData(){
    this.data.getData().subscribe(empData=>{
        this.employService = empData['msg'];
        console.log(this.employService)
    })
    console.log("Home component is working !")
    }
    
  25. If everything is ok then go to your browser and open the console and see the data return like below
  26. data
  27. Now go to the home.component.html and display the data from database
  28. <tbody> <tr *ngFor="let employServices of employService"> <td> {{employServices._id}}</td> <td> {{employServices.name}}</td> <td> {{employServices.emp_Id}}</td> <td> {{employServices.email}}</td> <td> {{employServices.address}} </td> <td> <button class="btn btn-danger"><i class="far fa-trash-alt"></i></button> <button class="btn btn-primary"><i class="fas fa-pen"></i></button> </td> </tr> </tbody>

    Create New Employ

  29. First go to the data.service.ts file and add the function below for sending data to server
  30. addEmploy(employ){ let headers = new HttpHeaders(); headers.append('Content-Type', 'application/json'); const baseUri = 'http://localhost:2003/employ/create'; return this.http.post(baseUri, employ,{headers:headers}).pipe(map(result => result)); }
  31. Then go to the component folder and create a new file called empadd by the command below in terminal
  32. ng g component empadd
    
  33. When you will be create / generate any component by command line, it's automatically import this component in app.module.ts file.
  34. Go to the app.module.ts file and add a new route path for EmpaddComponent like below
  35. const appRoutes:Routes = [ {path: '', component: HomeComponent}, {path: 'empadd', component: EmpaddComponent} ]
  36. Go to home.component.html file and add a button for add new employ
  37. <a class="btn btn-primary" (click)="addEmp($event)">Add Employ</a>
  38. Go to home.component.ts file and import Router module and then inject it in constructor
  39. import {Router} from '@angular/router'; And constructor( private router:Router, ) { }
  40. Then go to home.component.ts file and add click function for taking you in add employee form
  41. addEmp(event:any){ event.preventDefault(); this.router.navigate(['/empadd']) }
  42. Go to empadd.component.html file and add the HTML form below And
  43. <div class="container"> <h1 class="page-header">Add Employ Form</h1> <form (submit)="addEmpSubmit()"> <div class="form-group"> <label>Name</label> <input type="text" [(ngModel)]="name" name="name" class="form-control"> </div> <div class="form-group"> <label>Emp Id</label> <input type="text" [(ngModel)]="emp_Id" name="emp_Id" class="form-control"> </div> <div class="form-group"> <label>Email</label> <input type="text" [(ngModel)]="email" name="email" class="form-control"> </div> <div class="form-group"> <label>Address</label> <input type="text" [(ngModel)]="address" name="address" class="form-control"> </div> <input type="submit" class="btn btn-primary" value="Submit"> </form> </div>
  44. Go to empadd.component.ts file and import DataService and Router module and then inject it in constructor like below
  45. import { DataService } from '../../services/data.service'; import {Router} from '@angular/router'; And constructor( private dataService:DataService, private router:Router ) { }
  46. Then add the addEmpSubmit function below
  47. name:String; emp_Id:String; email:String; address:String; addEmpSubmit(){ const employ = { name: this.name, emp_Id: this.emp_Id, email: this.email, address: this.address } this.dataService.addEmploy(employ).subscribe(data=>{ console.log("Employ Added Successfully!"); this.router.navigate(['/']) },error=>{ console.log("Employ Added Faile!") }) }
  48. Now go to your browser and open console and see an Template parse errors: error. Because Can't bind to 'ngModel' since it isn't a known property of 'input'. Ok let's go now fixed this error
  49. Opne app.module.ts file and import Angular form module and also define it in NgModule > inputs array
  50. import {FormsModule} from '@angular/forms';
  51. Now see the console error is gone and now try to add new employ
  52. Go to your browser and click Add Employ button
  53. addButton
  54. Then you can see a simple employ add form like below
  55. add-employ-form
  56. Input all information and submit and see console Employ Added Successfully! report
  57. employ-added-successfully

    Update Employ

  58. Go to the component folder and create a new file called empupdate by the command below
  59. ng g component empupdate
    
  60. Go to the app.module.ts file and add the empupdate component path into appRoutes array like below
  61. const appRoutes:Routes = [ {path: '', component: HomeComponent}, {path: 'empadd', component: EmpaddComponent}, {path: 'empupdate', component: EmpupdateComponent} ]
  62. Go to the home.component.html file and add a click event (click)="updateEmp(employServices)" into the Update button like below.
  63. <button class="btn btn-primary" (click)="updateEmp(employServices)"><i class="fas fa-pen"></i></button>
  64. Open the home.component.ts file and then add the click function below
  65. updateEmp(employServices){ this.router.navigate(['/empupdate']) }
  66. Then go to the browser and click the update / edit button and see router is working or not. If everything is ok, then go to the next step.
  67. update button
  68. Now go to the data.service.ts file and add updateEmp function with employService parameter for update data into into database
  69. updateEmp(employService:EmployService){ let headers = new HttpHeaders(); headers.append('Content-Type', 'application/json'); const baseUri = 'http://localhost:2003/employ/update/'; return this.http.put(baseUri, employService, {headers:headers}); }
  70. Then add another two function setter and getter like below
  71. setter(employService:EmployService){ this.employService = employService; } getter(){ return this.employService; }
  72. Then go to empupdate.component.html file and add the update form below
  73. <div class="container"> <h1 class="page-header">Update Employ</h1> <form (submit)="updateEmpSubmit()"> <div class="form-group"> <label>Id</label> <input type="text" [(ngModel)]="employService._id" name="_id" class="form-control"> </div> <div class="form-group"> <label>Name</label> <input type="text" [(ngModel)]="employService.name" name="name" class="form-control"> </div> <div class="form-group"> <label>Emp Id</label> <input type="text" [(ngModel)]="employService.emp_Id" name="emp_Id" class="form-control"> </div> <div class="form-group"> <label>Email</label> <input type="text" [(ngModel)]="employService.email" name="email" class="form-control"> </div> <div class="form-group"> <label>Address</label> <input type="text" [(ngModel)]="employService.address" name="address" class="form-control"> </div> <input type="submit" class="btn btn-primary" value="Submit"> </form> </div>
  74. Then go to empupdate.component.ts file and import the Router module, DataService and EmployService like below
  75. import {Router} from '@angular/router'; import {DataService} from '../../services/data.service'; import {EmployService} from '../../services/employ.service';
  76. Then add a employService property like below
  77. private employService : EmployService;
  78. Then inject the dataService and router service into the constructor like below
  79. constructor( private dataService:DataService, private router:Router ) { }
  80. Then initialized the employService and for that pass the employService into the ngOnInit() function like below
  81. ngOnInit() { this.employService = this.dataService.getter(); }
  82. And then add the updateEmpSubmit() function like below
  83. updateEmpSubmit(){ if(this.employService._id != undefined){ this.dataService.updateEmp(this.employService).subscribe(data=>{ console.log('Successfully updated employ!'); this.router.navigate(['/']) },error=>{ console.log('Failed updated employ!'); }) } }
  84. Finally add the setter option into home.component.ts file into the updateEmp() function like below
  85. updateEmp(employServices){ this.data.setter(employServices); this.router.navigate(['/empupdate']) }
  86. Go to the browser and test it
  87. Update employ data

    Delete Employ

  88. First go to the data.service.ts file and add the deletePortfolio(id:string) function for delete employ data from database like below
  89. deleteEmp(id:string){ let headers = new HttpHeaders(); headers.append('Content-Type', 'application/json'); const baseUri = "http://localhost:2003/employ/delete/"; //const baseUri = "http://localhost:8080/portfolio/deleteportfolio/"; return this.http.delete(baseUri+id, {headers:headers}); }
  90. Then go to home.component.html file and add a click event (click)="doDelete(employServices) into delete button like below
  91. <button class="btn btn-danger" (click)="doDelete(employServices)"><i class="far fa-trash-alt"></i></button>
  92. Then go to home.component.ts file and add the delete function like below
  93. doDelete(employServices){ this.data.deleteEmp(employServices._id).subscribe(data=>{ this.employService.splice(this.employService.indexOf(employServices),1); console.log("Delete Success") }, error=>{ console.log("Delete Faile") }) }
  94. Finally go to browser and check it
  95. Delete employ

Contact

Md. Al Imran Islam
(Software Engineer)

imran.meanstack@gmail.com

meanstackfundamental.com

Al-imran

01751888673