Angular 8 - CRUD Operations - Part Three

This is the continuation of Angular 8 - CRUD Operations - Part One and Angular 8 - CRUD Operations - Part 2. In this article, we will learn how to implement CRUD operations using Angular and how to pass data through an Angular service to the database.
 
So far, we have covered  Web API, Angular Routing, and Services. Now let’s implement CRUD operations in Angular components.
 
First install the given packages, because I am going to use these in my sample application.
 
Bootstrap

npm install bootstrap –-save
 
JQuery

npm install jquery --save
 
Material JS

npm install --save @angular/material
 
Font Awesome

npm install font-awesome –save
 
Some important angular cli commands,
 
To create new class

ng generate class Employee
 
To create new service

ng generate service employee
 
To create new component

ng generate component header
 
To run the application

ng serve
 
Once you've  installed the above-given packages, you need to add q reference of Bootstrap in Angular.json like this:
  1. "styles": [  
  2.              "src/styles.scss",  
  3.              "node_modules/bootstrap/dist/css/bootstrap.min.css"  
  4.            ],  
  5.            "scripts": [  
  6.              "node_modules/jquery/dist/jquery.min.js",  
  7.              "node_modules/bootstrap/dist/js/bootstrap.min.js"  
  8.            ]  
Add stylesheets refrence in styles.scss file.
  1. /* You can add global styles to this file, and also import other style files */  
  2. @import "~bootstrap/dist/css/bootstrap.css";  
  3. // @import '@angular/material/prebuilt-themes/indigo-pink.css';  
  4. @import '@angular/material/prebuilt-themes/deeppurple-amber.css';  
Go to terminal and create a new class:
 
Angular 8 - CRUD Operations
  1. export class Employee {  
  2.     EmployeeID: number;  
  3.     LastName: string;  
  4.     FirstName: string;  
  5.     Title: string;  
  6.     TitleOfCourtesy: string;  
  7.     BirthDate: Date;  
  8.     HireDate: Date;  
  9.     Address: string;  
  10.     City: string;  
  11.     Region: string;  
  12.     PostalCode: string;  
  13.     Country: string;  
  14.     HomePhone: string;  
  15.     Extension: string;  
  16.     Photo: string;  
  17.     Notes: string;  
  18. }  
Add a new component
Angular 8 - CRUD Operations 
 
Add the following code in component and add the service and class refrence and CRUD functions in component.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { FormBuilder, Validators } from '@angular/forms';  
  3. import { Observable } from 'rxjs';  
  4. import { EmployeeService } from '../employee.service';  
  5. import { Employee } from '../employee';  
  6.   
  7. @Component({  
  8.   selector: 'app-employee',  
  9.   templateUrl: './employee.component.html',  
  10.   styleUrls: ['./employee.component.scss']  
  11. })  
  12. export class EmployeeComponent implements OnInit {  
  13.   dataSaved = false;  
  14.   employeeForm: any;  
  15.   allEmployees: Observable<Employee[]>;  
  16.   employeeIdUpdate = null;  
  17.   massage = null;  
  18.   
  19.   constructor(private formbulider: FormBuilder,   
  20.               private employeeService: EmployeeService) { }  
  21.   
  22.   ngOnInit() {  
  23.     this.employeeForm = this.formbulider.group({  
  24.       LastName: ['', [Validators.required]],  
  25.       FirstName: ['', [Validators.required]],  
  26.       Title: [''''],  
  27.       TitleOfCourtesy: [''''],  
  28.       BirthDate: ['', [Validators.required]],  
  29.       HireDate: [''''],  
  30.       Address: ['', [Validators.required]],  
  31.       City: ['', [Validators.required]],  
  32.       Region: ['', [Validators.required]],  
  33.       PostalCode: ['', [Validators.required]],  
  34.       Country: ['', [Validators.required]],  
  35.       HomePhone: ['', [Validators.required]],  
  36.       Notes: ['', [Validators.required]],  
  37.     });  
  38.     this.loadEmployees();  
  39.   }  
  40.   loadEmployees() {  
  41.     this.allEmployees = this.employeeService.getEmployees();  
  42.   }  
  43.   onFormSubmit() {  
  44.     this.dataSaved = false;  
  45.     const employee = this.employeeForm.value;  
  46.     this.CreateEmployee(employee);  
  47.     this.employeeForm.reset();  
  48.   }  
  49.   loadEmployee(employeeId: string) {  
  50.     this.employeeService.getEmployee(employeeId).subscribe(employee => {  
  51.       this.massage = null;  
  52.       this.dataSaved = false;  
  53.       this.employeeIdUpdate = employee.EmployeeID;  
  54.       this.employeeForm.controls['LastName'].setValue(employee.LastName);  
  55.       this.employeeForm.controls['FirstName'].setValue(employee.FirstName);  
  56.       this.employeeForm.controls['Title'].setValue(employee.Title);  
  57.       this.employeeForm.controls['TitleOfCourtesy'].setValue(employee.TitleOfCourtesy);  
  58.       this.employeeForm.controls['BirthDate'].setValue(employee.BirthDate);  
  59.       this.employeeForm.controls['HireDate'].setValue(employee.HireDate);  
  60.       this.employeeForm.controls['Address'].setValue(employee.Address);  
  61.       this.employeeForm.controls['City'].setValue(employee.City);  
  62.       this.employeeForm.controls['Region'].setValue(employee.Region);  
  63.       this.employeeForm.controls['PostalCode'].setValue(employee.PostalCode);  
  64.       this.employeeForm.controls['Country'].setValue(employee.Country);  
  65.       this.employeeForm.controls['HomePhone'].setValue(employee.HomePhone);  
  66.       this.employeeForm.controls['Notes'].setValue(employee.Notes);  
  67.     });  
  68.   
  69.   }  
  70.   CreateEmployee(employee: Employee) {  
  71.     if (this.employeeIdUpdate == null) {  
  72.       this.employeeService.createEmployee(employee).subscribe(  
  73.         () => {  
  74.           this.dataSaved = true;  
  75.           this.massage = 'Record saved Successfully';  
  76.           this.loadEmployees();  
  77.           this.employeeIdUpdate = null;  
  78.           this.employeeForm.reset();  
  79.         }  
  80.       );  
  81.     } else {  
  82.       employee.EmployeeID = this.employeeIdUpdate;  
  83.       this.employeeService.updateEmployee(employee).subscribe(() => {  
  84.         this.dataSaved = true;  
  85.         this.massage = 'Record Updated Successfully';  
  86.         this.loadEmployees();  
  87.         this.employeeIdUpdate = null;  
  88.         this.employeeForm.reset();  
  89.       });  
  90.     }  
  91.   }  
  92.    
  93.   deleteEmployee(employeeId: string) {  
  94.     if (confirm("Are you sure you want to delete this ?")) {    
  95.     this.employeeService.deleteEmployee(employeeId).subscribe(() => {  
  96.       this.dataSaved = true;  
  97.       this.massage = 'Record Deleted Succefully';  
  98.       this.loadEmployees();  
  99.       this.employeeIdUpdate = null;  
  100.       this.employeeForm.reset();  
  101.     });  
  102.   }    
  103. }  
  104. resetForm() {  
  105.   this.employeeForm.reset();  
  106.   this.massage = null;  
  107.   this.dataSaved = false;  
  108. }  
  109. }  
Add the following html in employee.compnent.html:
  1. <div class="container">  
  2.     <mat-card>  
  3.       <mat-toolbar color="accent">  
  4.         <div align="center" style="color:white;text-align: right;">      
  5.           CRUD operation in Angular 8  
  6.         </div>         
  7.       </mat-toolbar>  
  8.     <br><br>  
  9.       <mat-card-content>  
  10.         <form [formGroup]="employeeForm" (ngSubmit)="onFormSubmit(employeeForm.value)">  
  11.                 <table>  
  12.                   <tr>  
  13.                     <td class="tbl1">  
  14.                       <mat-form-field class="demo-full-width">  
  15.                         <input formControlName="LastName" matTooltip="Enter Last Name" matInput placeholder="Last Name">                          
  16.                       </mat-form-field>  
  17.                       <mat-error>  
  18.                         <span *ngIf="!employeeForm.get('LastName').value && employeeForm.get('LastName').touched"></span>                          
  19.                       </mat-error>  
  20.                     </td>  
  21.                     <td class="tbl1">  
  22.                       <mat-form-field class="demo-full-width">                          
  23.                         <input formControlName="FirstName" matTooltip="Enter First Name" matInput placeholder="First Name">  
  24.                       </mat-form-field>  
  25.                       <mat-error>                          
  26.                         <span *ngIf="!employeeForm.get('FirstName').value && employeeForm.get('FirstName').touched"></span>  
  27.                       </mat-error>  
  28.                     </td>  
  29.                     <td class="tbl1">  
  30.                       <mat-form-field class="demo-full-width">                          
  31.                         <input formControlName="Title" matTooltip="Enter Title" matInput placeholder="Title">  
  32.                       </mat-form-field>  
  33.                       <mat-error>                          
  34.                         <span *ngIf="!employeeForm.get('Title').value && employeeForm.get('Title').touched"></span>  
  35.                       </mat-error>  
  36.                     </td>                     
  37.                   </tr>  
  38.                   <tr>  
  39.                     <td class="tbl1">  
  40.                       <!-- <mat-form-field class="demo-full-width">                          
  41.                         <input formControlName="TitleOfCourtesy" matTooltip="Enter Title Of Courtesy" matInput placeholder="Title Of Courtesy">  
  42.                       </mat-form-field> -->  
  43.                       <mat-form-field>                          
  44.                         <select matNativeControl formControlName="TitleOfCourtesy" matTooltip="Enter Title Of Courtesy" matInput placeholder="Title Of Courtesy">  
  45.                           <option value="Ms.">Ms.</option>  
  46.                           <option value="Dr.">Dr.</option>  
  47.                           <option value="Mrs.">Mrs.</option>  
  48.                           <option value="Mr.">Mr.</option>  
  49.                         </select>  
  50.                       </mat-form-field>  
  51.                       <mat-error>                          
  52.                         <span *ngIf="!employeeForm.get('TitleOfCourtesy').value && employeeForm.get('TitleOfCourtesy').touched"></span>  
  53.                       </mat-error>  
  54.                     </td>  
  55.                     <td class="tbl1" colspan="2">  
  56.                       <mat-form-field class="demo-full-width">  
  57.                         <input matInput [matDatepicker]="picker" matTooltip="Enter Date Of Birth" formControlName="BirthDate" placeholder="Date Of Birth">  
  58.                         <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>  
  59.                         <mat-datepicker #picker></mat-datepicker>  
  60.                       </mat-form-field>  
  61.                       <mat-error>  
  62.                         <span *ngIf="!employeeForm.get('BirthDate').value && employeeForm.get('BirthDate').touched"></span>  
  63.                       </mat-error>  
  64.                     </td>  
  65.                     <td class="tbl1">                        
  66.                     </td>                     
  67.                   </tr>  
  68.                   <tr>  
  69.                     <td class="tbl1">  
  70.                       <mat-form-field class="demo-full-width">  
  71.                         <input matTooltip="Enter Address" formControlName="Address" matInput placeholder="Address">  
  72.                       </mat-form-field>  
  73.                       <mat-error>  
  74.                         <span *ngIf="!employeeForm.get('Address').value && employeeForm.get('Address').touched"></span>  
  75.                       </mat-error>  
  76.                     </td>  
  77.                     <td class="tbl1">  
  78.                       <mat-form-field class="demo-full-width">  
  79.                         <input formControlName="City" matTooltip="Enter City" matInput placeholder="City">  
  80.                       </mat-form-field>  
  81.                       <mat-error>  
  82.                         <span *ngIf="!employeeForm.get('City').value && employeeForm.get('City').touched"></span>  
  83.                       </mat-error>  
  84.                     </td>  
  85.                     <td class="tbl1">  
  86.                       <mat-form-field class="demo-full-width">  
  87.                         <input formControlName="Region" matTooltip="Enter Region" matInput placeholder="Region">  
  88.                       </mat-form-field>  
  89.                       <mat-error>  
  90.                         <span *ngIf="!employeeForm.get('Region').value && employeeForm.get('Region').touched"></span>  
  91.                       </mat-error>  
  92.                     </td>  
  93.                   </tr>  
  94.                   <tr>  
  95.                     <td class="tbl1">  
  96.                       <mat-form-field class="demo-full-width">  
  97.                         <input formControlName="PostalCode" matTooltip="Enter Postal Code" matInput placeholder="Postal Code">  
  98.                       </mat-form-field>  
  99.                       <mat-error>  
  100.                         <span *ngIf="!employeeForm.get('PostalCode').value && employeeForm.get('PostalCode').touched"></span>  
  101.                       </mat-error>  
  102.                     </td>  
  103.                     <td class="tbl1">  
  104.                       <mat-form-field class="demo-full-width">  
  105.                         <input formControlName="Country" matTooltip="Enter Country" matInput placeholder="Country">  
  106.                       </mat-form-field>  
  107.                       <mat-error>  
  108.                         <span *ngIf="!employeeForm.get('Country').value && employeeForm.get('Country').touched"></span>  
  109.                       </mat-error>  
  110.                     </td>  
  111.                     <td class="tbl1">  
  112.                       <mat-form-field class="demo-full-width">  
  113.                         <input formControlName="HomePhone" matTooltip="Enter Home Phone" matInput placeholder="Home Phone">  
  114.                       </mat-form-field>  
  115.                       <mat-error>  
  116.                         <span *ngIf="!employeeForm.get('HomePhone').value && employeeForm.get('HomePhone').touched"></span>  
  117.                       </mat-error>  
  118.                     </td>  
  119.                   </tr>  
  120.                   <tr>  
  121.                     <td class="tbl1" colspan="3">  
  122.                       <mat-form-field class="demo-full-width">  
  123.                         <input formControlName="Notes" matTooltip="Enter Notes" matInput placeholder="Notes">  
  124.                       </mat-form-field>  
  125.                       <mat-error>  
  126.                         <span *ngIf="!employeeForm.get('Notes').value && employeeForm.get('Notes').touched"></span>  
  127.                       </mat-error>  
  128.                     </td>  
  129.                   </tr>  
  130.                   <tr>  
  131.                     <td></td>  
  132.                     <td  class="content-center">  
  133.                       <button type="submit" mat-raised-button color="accent" matTooltip="Click Submit Button" [disabled]="!employeeForm.valid">Submit</button>      
  134.                       <button type="reset" mat-raised-button color="accent" matTooltip="Click Reset Button" (click)="resetForm()">Reset</button>  
  135.                     </td>  
  136.                     <td>  
  137.                       <p *ngIf="dataSaved" style="color:rgb(0, 128, 0);font-size:20px;font-weight:bold" Class="success" align="left">  
  138.                         {{massage}}  
  139.                       </p>  
  140.                     </td>  
  141.                   </tr>  
  142.                 </table>  
  143.     <br><br>  
  144.           <table class="table" >  
  145.               <tr ngclass="btn-primary">  
  146.                 <th class="tbl2">Last Name</th>  
  147.                 <th class="tbl2">First Name</th>  
  148.                 <th class="tbl2">Date Of Birth</th>  
  149.                 <th class="tbl2">Hire Date</th>  
  150.                 <th class="tbl2">City</th>  
  151.                 <!-- <th class="tbl2">Gender</th> -->  
  152.                 <th class="tbl2">Region</th>  
  153.                 <th class="tbl2">Postal Code</th>  
  154.                 <th class="tbl2">Country</th>  
  155.                 <th class="tbl2">Edit</th>  
  156.                 <th class="tbl2">Delete</th>  
  157.               </tr>  
  158.               <tr *ngFor="let employee of allEmployees | async">  
  159.                 <td class="tbl2">{{employee.LastName}}</td>  
  160.                 <td class="tbl2">{{employee.FirstName}}</td>  
  161.                 <td class="tbl2">{{employee.BirthDate | date }}</td>  
  162.                 <td class="tbl2">{{employee.HireDate | date }}</td>  
  163.                 <td class="tbl2">{{employee.City}}</td>  
  164.                 <!-- <td class="tbl2">{{employee.Gender ==0? 'Male' : 'Female'}}</td> -->  
  165.                 <td class="tbl2">{{employee.Region}}</td>  
  166.                 <td class="tbl2">{{employee.PostalCode}}</td>  
  167.                 <td class="tbl2">{{employee.Country}}</td>  
  168.                 <td class="tbl2">  
  169.                   <button type="button" class="btn btn-info" matTooltip="Click Edit Button" (click)="loadEmployee(employee.EmployeeID)">Edit</button>  
  170.                 </td>  
  171.                 <td class="tbl2">  
  172.                   <button type="button" class="btn btn-danger" matTooltip="Click Delete Button" (click)="deleteEmployee(employee.EmployeeID)">Delete</button>  
  173.                 </td>  
  174.               </tr>      
  175.             </table>      
  176.         </form>  
  177.       </mat-card-content>  
  178.     </mat-card>      
  179.     </div>  
Add the component and class and other references in app.module.ts file.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';  
  4. import { HttpClientModule, HttpClient } from '@angular/common/http';  
  5. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  6. import {  
  7.   MatButtonModule, MatMenuModule, MatDatepickerModule, MatNativeDateModule , MatIconModule, MatCardModule, MatSidenavModule, MatFormFieldModule,  
  8.   MatInputModule, MatTooltipModule, MatToolbarModule  
  9. } from '@angular/material';  
  10. import { MatRadioModule } from '@angular/material/radio';  
  11. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
  12.   
  13. import { AppRoutingModule } from './app-routing.module';  
  14. import { AppComponent } from './app.component';  
  15. import { NavbarComponent } from './navbar/navbar.component';  
  16. import { EmployeeComponent } from './employee/employee.component';  
  17. import { AboutComponent } from './about/about.component';  
  18. import { FooterComponent } from './footer/footer.component';  
  19. import { HeaderComponent } from './header/header.component';  
  20. import { EmployeeService } from './employee.service';  
  21.   
  22. @NgModule({  
  23.   declarations: [  
  24.     AppComponent,  
  25.     NavbarComponent,  
  26.     EmployeeComponent,  
  27.     AboutComponent,  
  28.     FooterComponent,  
  29.     HeaderComponent  
  30.   ],  
  31.   imports: [  
  32.     BrowserModule,  
  33.     AppRoutingModule,  
  34.     FontAwesomeModule,  
  35.     HttpClientModule,  
  36.     FormsModule,  
  37.     ReactiveFormsModule,  
  38.     HttpClientModule,  
  39.     BrowserAnimationsModule,  
  40.     MatButtonModule,  
  41.     MatMenuModule,  
  42.     MatDatepickerModule,  
  43.     MatNativeDateModule,  
  44.     MatIconModule,  
  45.     MatRadioModule,  
  46.     MatCardModule,  
  47.     MatSidenavModule,  
  48.     MatFormFieldModule,  
  49.     MatInputModule,  
  50.     MatTooltipModule,  
  51.     MatToolbarModule,  
  52.   ],  
  53.   providers: [EmployeeService, HttpClientModule, MatDatepickerModule],  
  54.   bootstrap: [AppComponent]  
  55. })  
  56. export class AppModule { }  
Run the application.
 
Angular 8 - CRUD Operations
 
Open http://localhost:4200/ in browser.
 
Angular 8 - CRUD Operations
 
On the page, you have a list of employees and options to create a new employee and edit an existing employee and delete an employee. As you can see, we have used Bootstrap and material.js for layout styling. For example, when you click on a last name then then you will see tooltip and validation color.
 
Angular 8 - CRUD Operations
 
Click on the little calendar icon to see the calendar.
 
Angular 8 - CRUD Operations
 

Conclusion

 
In this article, we have learned the CRUD operations using Angular with Web API and Entity Framework with SQL Server data. I have  attached sample application source code and Web API code separately.


Similar Articles