Updated : Nov 26, 2019 in Angular

Angular 8 crud operation example using web API

In this article, we will learn how to perform an Angular 8 crud operation example using web API

create a root directory(customer ) in your project, you will implement web pis for curd and Add the given below code

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {CustomerCrudComponent} from '../app/customer-crud/customer-crud.component'

const routes: Routes = [
  {path:"crud",component:CustomerCrudComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClient,HttpClientModule, HttpHeaders } from '@angular/common/http'; 
import { CommonModule } from '@angular/common';
import { ToastrModule } from 'ngx-toastr';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import {A11yModule} from '@angular/cdk/a11y';
import {DragDropModule} from '@angular/cdk/drag-drop';
import {PortalModule} from '@angular/cdk/portal';
import {ScrollingModule} from '@angular/cdk/scrolling';
import {CdkStepperModule} from '@angular/cdk/stepper';
import {CdkTableModule} from '@angular/cdk/table';
import {CdkTreeModule} from '@angular/cdk/tree';

import {
  MatAutocompleteModule,
  MatBadgeModule,
  MatBottomSheetModule,
  MatButtonModule,
  MatButtonToggleModule,
  MatCardModule,
  MatCheckboxModule,
  MatChipsModule,
  MatDatepickerModule,
  MatDialogModule,
  MatDividerModule,
  MatExpansionModule,
  MatGridListModule,
  MatIconModule,
  MatInputModule,
  MatListModule,
  MatMenuModule,
  MatNativeDateModule,
  MatPaginatorModule,
  MatProgressBarModule,
  MatProgressSpinnerModule,
  MatRadioModule,
  MatRippleModule,
  MatSelectModule,
  MatSidenavModule,
  MatSliderModule,
  MatSlideToggleModule,
  MatSnackBarModule,
  MatSortModule,
  MatStepperModule,
  MatTableModule,
  MatTabsModule,
  MatToolbarModule,
  MatTooltipModule,
  MatTreeModule,
} from '@angular/material';
import { CustomerCrudComponent } from './customer-crud/customer-crud.component';
import { CustomerService } from './customer.service';

@NgModule({
  declarations: [
    AppComponent,
    CustomerCrudComponent,
    
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,CommonModule,ToastrModule.forRoot(),
    FormsModule,ReactiveFormsModule,
    AppRoutingModule,
    HttpClientModule,
    A11yModule,
    CdkStepperModule,
    CdkTableModule,
    CdkTreeModule,
    DragDropModule,
    MatAutocompleteModule,
    MatBadgeModule,
    MatBottomSheetModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatCardModule,
    MatCheckboxModule,
    MatChipsModule,
    MatStepperModule,
    MatDatepickerModule,
    MatDialogModule,
    MatDividerModule,
    MatExpansionModule,
    MatGridListModule,
    MatIconModule,
    MatInputModule,
    MatListModule,
    MatMenuModule,
    MatNativeDateModule,
    MatPaginatorModule,
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatRippleModule,
    MatSelectModule,
    MatSidenavModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatSnackBarModule,
    MatSortModule,
    MatTableModule,
    MatTabsModule,
    MatToolbarModule,
    MatTooltipModule,
    MatTreeModule,
    PortalModule,
    ScrollingModule,
  ],
  providers: [CustomerService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Customer.Model.ts

export interface Customer
{
    Id:number;
    Name:string;
    Phone:string;
    Email:string;
    Notes:number;
    Gender:string;
}

customer.service.ts

import { Injectable } from '@angular/core';
import { HttpClient,HttpClientModule, HttpHeaders } from '@angular/common/http';  
import { Observable, of, throwError, pipe} from "rxjs"
import { map, filter, catchError, mergeMap } from 'rxjs/operators';

import { Customer } from '../app/models/Customer.Model'

@Injectable({
  providedIn: 'root'
})
export class CustomerService {
  public apiURL:string="http://localhost:89506/api/customers";
  constructor(private httpClient:HttpClient) { }


  // Create =C
  insertCustomer(inputCustomer:Customer)
  {
    return this.httpClient.post(this.apiURL,inputCustomer)
    .pipe(
      map(res => res),
       catchError( this.errorHandler)
      );
  }
  // Read=R
  getAllCustomers ()
  {
    return this.httpClient.get(this.apiURL)
    .pipe(
      map(res => res),
       catchError( this.errorHandler)
      );
  }
  // Update=U
  updateCustomer(inputCustomer:Customer,id:number)
  {
    return this.httpClient.put(this.apiURL+"/"+id,inputCustomer)
    .pipe(
      map(res => res),
       catchError( this.errorHandler)
      );
  }
  // Delete =D
  deleteCustomer(id:number)
  {
    return this.httpClient.delete(this.apiURL+"/"+id)
    .pipe(
      map(res => res),
       catchError( this.errorHandler)
      );
  }
  errorHandler(error: Response) {  
    console.log(error);  
    return throwError(error);  
} 
}

the above customer.service.ts file you will change your API URL

customer.service.spec.ts

import { TestBed } from '@angular/core/testing';

import { CustomerService } from './customer.service';

describe('CustomerService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: CustomerService = TestBed.get(CustomerService);
    expect(service).toBeTruthy();
  });
});

customer-crud.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { CustomerCrudComponent } from './customer-crud.component';

describe('CustomerCrudComponent', () => {
  let component: CustomerCrudComponent;
  let fixture: ComponentFixture<CustomerCrudComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CustomerCrudComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CustomerCrudComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

customer-crud.component.ts

import { Component, OnInit, Input,ChangeDetectionStrategy } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SelectionModel } from '@angular/cdk/collections';
import { MatTableDataSource } from '@angular/material/table';
import { ToastrService } from 'ngx-toastr';

import { IAlert } from '../models/IAlert'
import { CustomerService } from '../customer.service';
import { Customer } from '../models/Customer.Model';
//This is crud tutorial designed  by DotNet Techy YouTube Channel

@Component({
  selector: 'app-customer-crud',
  templateUrl: './customer-crud.component.html',
  styleUrls: ['./customer-crud.component.scss'],
  changeDetection:ChangeDetectionStrategy.Default
})
export class CustomerCrudComponent implements OnInit {

  displayedColumns: string[] = ['Id', 'Name', 'Phone', 'Email', 'Notes', 'Gender'];
  public ELEMENT_DATA: Customer[];

  selection = new SelectionModel<Customer>(false, []);

  insertCustomerForm: FormGroup;
  updateCustomerForm: FormGroup;
  deleteCustomerForm: FormGroup;

  @Input()
  public alerts: Array<IAlert> = [];
  public globalResponse: any;
  public customers: Customer[];
  public currentRow: Customer[];
  dataSource = new MatTableDataSource<Customer>(this.customers);
  gen = "";
  selectedValue="";
  selectedValueUpdate="";
  selectedValueDelete="";
  gender = [
    { key: 1, value: 'Male' },
    { key: 2, value: 'Female' },
  ];

  /** Whether the number of selected elements matches the total number of rows. */
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.dataSource.data.forEach(row => this.selection.select(row));
  }
  /** The label for the checkbox on the passed row */
  checkboxLabel(row?: Customer): string {
    this.currentRow = this.selection.selected;
    console.log(this.currentRow.length);
    if (!row) {
      return `${this.isAllSelected() ? 'select' : 'deselect'} all`;
    }
    if (this.currentRow.length > 0) {
      //Set Update form
      this.updateCustomerForm.controls["Id"].setValue(this.currentRow[0].Id);
      this.updateCustomerForm.controls["Name"].setValue(this.currentRow[0].Name);
      this.updateCustomerForm.controls["Phone"].setValue(this.currentRow[0].Phone);
      this.updateCustomerForm.controls["Email"].setValue(this.currentRow[0].Email);
      this.updateCustomerForm.controls["Notes"].setValue(this.currentRow[0].Notes);
      this.selectedValueUpdate=this.currentRow[0].Gender;
      this.updateCustomerForm.controls["Gender"].setValue(this.selectedValueUpdate);

      //Set delete form
      this.deleteCustomerForm.controls["Id"].setValue(this.currentRow[0].Id);
      this.deleteCustomerForm.controls["Name"].setValue(this.currentRow[0].Name);
      this.deleteCustomerForm.controls["Phone"].setValue(this.currentRow[0].Phone);
      this.deleteCustomerForm.controls["Email"].setValue(this.currentRow[0].Email);
      this.deleteCustomerForm.controls["Notes"].setValue(this.currentRow[0].Notes);
      this.selectedValueDelete=this.currentRow[0].Gender;
      this.deleteCustomerForm.controls["Gender"].setValue(this.selectedValueDelete);

    }
    return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.Id + 1}`;

  }

  constructor(private fb: FormBuilder, private customerService: CustomerService, private toastrService: ToastrService) {

  }

  ngOnInit() {
    this.OnRefreshCustomer();
    this.insertCustomerForm = this.fb.group({
      Name: ['', Validators.required],
      Email: ['', Validators.required],
      Phone: ['', Validators.required],
      Notes: ['',],
      Gender: ['', Validators.required],
    });
    this.updateCustomerForm = this.fb.group({
      Id: ['', Validators.required],
      Name: ['', Validators.required],
      Email: ['', Validators.required],
      Phone: ['', Validators.required],
      Notes: ['',],
      Gender: ['', Validators.required],
    });
    this.deleteCustomerForm = this.fb.group({
      Id: ['', Validators.required],
      Name: ['', Validators.required],
      Email: ['', Validators.required],
      Phone: ['', Validators.required],
      Notes: ['',],
      Gender: ['', Validators.required],
    });
  }

  // C-For Create
  OnSaveCustomer() {
    let inputCustomer = this.insertCustomerForm.value;
    console.log("Below is input customer.");

    inputCustomer.Gender = this.selectedValue;
    console.log(inputCustomer);

    this.customerService.insertCustomer(inputCustomer)
      .subscribe((result) => {
        this.globalResponse = result;
      },
        error => { //This is error part
          console.log(error.message);
          this.toastrService.error('error', 'Something went wrong while saving the product, Please try after sometime.');
        },
        () => {
          //  This is Success part
          this.toastrService.success('success', 'Customer has been saved successfully. Now you can add more customer , if you wish too.');
          this.insertCustomerForm.reset();
        }
      )
  }
  // R-For Read
  OnRefreshCustomer() {
    this.customerService.getAllCustomers()
      .subscribe((result) => {
        this.globalResponse = result;
      },
        error => { //This is error part
          console.log(error.message);
          this.toastrService.error('error', 'Something went wrong while getting the customers, Please try after sometime.');
        },
        () => {
          //  This is Success part
          this.toastrService.success('success', 'Customer data loaded successfully.');
          this.customers = this.globalResponse;
          this.dataSource = new MatTableDataSource<Customer>(this.customers);
          console.log("All records");
          console.log(this.customers);
          this.insertCustomerForm.reset();
          this.updateCustomerForm.reset();
          this.deleteCustomerForm.reset();

        }
      )
  }
  // U-For Update
  OnUpdateCustomer() {
    let inputCustomer = this.updateCustomerForm.value;
    console.log(inputCustomer);
    inputCustomer.Gender = this.selectedValueDelete;
    this.customerService.updateCustomer(inputCustomer, inputCustomer.Id)
      .subscribe((result) => {
        this.globalResponse = result;
      },
        error => { //This is error part
          console.log(error.message);
          this.toastrService.error('error', 'Something went wrong while getting the customers, Please try after sometime.');
        },
        () => {
          //  This is Success part
          this.toastrService.success('success', 'Customer has been updated successfully. Now you can update more customer , if you wish too.');
          this.updateCustomerForm.reset();
          this.deleteCustomerForm.reset();
        }
      )
  }
  // D-For Delete
  OnDeleteCustomer() {
    let inputCustomer = this.deleteCustomerForm.value;
    console.log(inputCustomer);
    this.customerService.deleteCustomer(inputCustomer.Id)
      .subscribe((result) => {
        this.globalResponse = result;
      },
        error => { //This is error part
          console.log(error.message);
          this.toastrService.error('error', 'Something went wrong while getting the customers, Please try after sometime.');
        },
        () => {
          //  This is Success part
          this.toastrService.success('success', 'Customer has been deleted successfully. Now you can delete more customer , if you wish too.');
          this.updateCustomerForm.reset();
          this.deleteCustomerForm.reset();
        }
      )
  }


}

customer-curd-component.html

<!DOCTYPE>
<html>
<head>
    <META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>

    <span>CRUD Operation In Angular 8, Tutorial By tutorial helper</span>
    Create Customer Form
    <div>
        <form target="_blank" onsubmit="try {return window.confirm("This form may not function properly due to certain security constraints.\nContinue?");} catch (e) {return false;}">
            <input>
            <input>
            <input>
            <textarea></textarea>
            {{gen.value}}
        </form>
    </div>

    <button color="primary" style="margin-left:45%">Save</button>

    <table>
        <th>
            <button color="warn">Refresh</button>
        </th>
        <td></td>
        <th> Name. </th>
        <td> {{element.Name}} </td>
        <th> Phone </th>
        <td> {{element.Phone}} </td>

        <th> Email </th>
        <td> {{element.Email}} </td>
        <th> Notes </th>
        <td> {{element.Notes}} </td>
        <th> Gender </th>
        <td> {{element.Gender}} </td>
        <tr></tr>
        <tr></tr>
    </table>
    Update Customer
    <div>
        <form target="_blank" onsubmit="try {return window.confirm("This form may not function properly due to certain security constraints.\nContinue?");} catch (e) {return false;}" >
            <input>
            <input>
            <input>
            <input>
            <textarea></textarea>
            {{gen.value}}
        </form>
    </div>

    <button color="accent" style="margin-left:45%">Update</button>
    Delete Customer
    <div>
        <form target="_blank" onsubmit="try {return window.confirm("This form may not function properly due to certain security constraints.\nContinue?");} catch (e) {return false;}" >
            <input>
            <input>
            <input>
            <input>

            <textarea></textarea>
            {{gen.value}}
        </form>
    </div>
    <button color="primary" style="margin-left:45%">Delete</button>
</body>
</html>

run your application

Angular 8 curd operation source code using web API
Angular 8 crud operation source code using web API

Leave a Reply

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