Skip to main content

Create an Angular application with CRUD operations for company and branch details with in-memory data:




Create an Angular application with CRUD operations for company and branch details with in-memory data:

This tutorial assumes that you have installed the necessary npm packages and the latest Angular version, and CLI version, 

To install the CLI for Angular use the following command,

npm install -g @angular/cli

then use the command

ng new CompanyBranchCRUD

The above command will create a directory ‘CompanyBranchCRUD’ and install necessary items

Once the installation is over then go the created directory

cd CompanyBranchCRUD

The following 3 steps is optional, this is for bootstrap, if you want to concentrate on functionality happy to skip these.
Step 1: npm install --save bootstrap@next If any error occurs then use npm install --save bootstrap
Step 2: Import the bootstrap in the style.css file @import "~bootstrap/dist/css/bootstrap.css";
Step 3: install the BootStarp components by issuing the command npm install --save @ng-bootstrap/ng-bootstrap 
Then import the NgbModule in the app.module.ts 
import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; 
Finally the app.module.ts should be like this

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule,ReactiveFormsModule  } from '@angular/forms';

import { AppComponent } from './app.component';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Then issue the command

ng serve

to see everything is working correct,

Try to open the following URL http://localhost:4200/ in the browser,

If you are seeing something like this, then our sample is working correctly,



Now we are going to apply the expected changes,

Step 1: Remove all the html from the app.component.html

Step 2 : Create a html like this

<div>
  <table class="table table-striped table-bordered table-hover">
  <tr>
    <td>
      Company Name
    </td>
    <td>
      <input type="text" name="myCompanyName" [(ngModel)]="CompName1" >
    </td>
  </tr>
  <tr>
    <td>
      Company Branch
    </td>
    <td>
      <input type="text" name="myCompanyAddress" [(ngModel)]="CompAddress1"  >
    </td>
  </tr>
  <tr>
    <td>
    </td>
    <td>
      <label style="color: red;" >{{ErrorMessage1}}</label>
    </td>
  </tr>
  <tr>
    <td>

    </td>
    <td>
      <button type="button" name="btnSubmit" (click)="submitForm()">{{SubmitButton}}</button>
    </td>
  </tr>
</table> 
</div>

<br>
<br>

<table class="table table-striped table-bordered table-hover">
<thead>
  <tr>
      <th>
          Company Number
              </th>
    <th>
Company Name
    </th>
    <th>
Company Address
    </th>
    <th>
      Edit
    </th>
    <th>
        Delete
      </th>
  </tr>
</thead>

<tbody>
  <tr *ngFor ="let comp of newCompanies">

      <td>
          {{comp.ClsCompanyID}}
        </td>

    <td>
      {{comp.ClsCompanyName}}
    </td>

    <td>
        {{comp.ClsCompanyAddress}}
      </td>

      <td>
        <button name="btnEdit" (click)="editCompany(comp.ClsCompanyID)">Edit</button>
      </td>

      <td>
          <button name="btnDelete" (click)="deleteCompany(comp.ClsCompanyID)">Delete</button>
        </td>

  </tr>
</tbody>

</table>

<br>
<br>

<button name="btnClear" (click)="clearInMemeory()">Clear In Memory</button>

[(ngModel)] will bind the data whatever it is getting assigned in the model

Step 3:

In the app.component.ts do the following

Create a class outside the main class AppComponent

export class ClsCompany{
  ClsCompanyID: number;
  ClsCompanyName : string;
  ClsCompanyAddress:string;
  constructor(
      public ClsCompanyID1:number,
      public ClsCompanyName1:string,
      public ClsCompanyAddress1:string 
    ){
    this.ClsCompanyID = ClsCompanyID1;
    this.ClsCompanyName = ClsCompanyName1;
    this.ClsCompanyAddress = ClsCompanyAddress1;
  }
}

Then declare and initialize the members,
  title = 'Sample Application!';
  SubmitButton:string;
  CompName1 :string='';
  CompAddress1:string ='';
  ErrorMessage1 : string='';
  newCompanies : Array<ClsCompany> ;
  NextID : number =0;

  currentManipulationID :number;

Leave the constructor as it as, as we are not doing anything in this

  constructor(){

  }



Create another function

  ngOnInit(){
    this.newCompanies = [];
    this.currentManipulationID = 9999;
    this.SubmitButton = 'Submit Form';
    this.ErrorMessage1 = '';
  }

And for console logging, error logging
logInfo(message:string){
    console.log('');
    console.log(message);
  }
  showError(message:string){
    this.ErrorMessage1 = message;
  }

And the other necessary business logic
isDuplicateExists(){
    let dupCompName =  this.newCompanies.find(
      X=>X.ClsCompanyName.toUpperCase()===this.CompName1.toUpperCase()
      &&
      X.ClsCompanyAddress.toUpperCase()===this.CompAddress1.toUpperCase());          
      if(dupCompName!=undefined){
        this.logInfo('Failed isDuplicateExists Test!');
        this.showError('Duplicate Entry, please enter details correctly!');
        return true;
      }else{
        this.logInfo('Passed isDuplicateExists Test!');
        this.showError('');
        return false;
      }
  }
  isDuplicateExistsForEdit(currentID: number){
    let dupCompName =  this.newCompanies.find(
      X=>X.ClsCompanyName.toUpperCase()==this.CompName1.toUpperCase()
      &&
      X.ClsCompanyAddress.toUpperCase()==this.CompAddress1.toUpperCase()
      &&
      X.ClsCompanyID!=this.currentManipulationID);          
      if(dupCompName!=undefined){
        this.logInfo('Failed isDuplicateExistsForEdit Test!');
        this.showError('Duplicate Entry, please enter details correctly!');
        return true;
      }else{
        this.logInfo('Passed isDuplicateExistsForEdit Test!');
        this.showError('');
        return false;
      }
  }
    submitForm(){   
    this.logInfo('In Initial Submit Form!');
  if(this.currentManipulationID ==9999){
    this.logInfo('In New Insert!');
      this.NextID = this.newCompanies.length+1;
 
      if(!this.isItemsEmpty()){
          if(!this.isDuplicateExists()){
              this.newCompanies.push(
                new ClsCompany(
                  this.NextID,
                  this.CompName1,
                  this.CompAddress1));
                  this.logInfo('New Insert Successful!');
            }
        }
      }
      else
      {
        if(!this.isItemsEmpty())
        {
          if(!this.isDuplicateExistsForEdit(this.currentManipulationID))
          {
            this.newCompanies.find(X=>X.ClsCompanyID==this.currentManipulationID).ClsCompanyName = this.CompName1;
            this.newCompanies.find(X=>X.ClsCompanyID==this.currentManipulationID).ClsCompanyAddress =this.CompAddress1;
            this.logInfo('Update Successful!');
            this.resetToInitialState();
          }
        }
      }
  }
  resetToInitialState(){
    this.CompName1 ='';
    this.CompAddress1='';
    this.currentManipulationID = 9999;
    this.SubmitButton = 'Submit Form';
    this.logInfo('Reset Initiated!');
  }
  editCompany(ClsID:number){
    this.currentManipulationID = this.newCompanies.find(X=>X.ClsCompanyID==ClsID).ClsCompanyID;
    this.CompName1 = this.newCompanies.find(X=>X.ClsCompanyID==ClsID).ClsCompanyName;
    this.CompAddress1 = this.newCompanies.find(X=>X.ClsCompanyID==ClsID).ClsCompanyAddress;
    this.logInfo('Update Initiated!');
    this.SubmitButton = 'Update Company Details';
  }
  deleteCompany(ClsID:number){
    this.currentManipulationID = this.newCompanies.find(X=>X.ClsCompanyID==ClsID).ClsCompanyID;
    let updateItem =  this.newCompanies.find(X=>X.ClsCompanyID==this.currentManipulationID);
    this.newCompanies = this.newCompanies.filter(X=>X!=updateItem);
    this.logInfo('Delete Successful!');
    this.resetToInitialState();   
  }
  clearInMemeory(){
    this.newCompanies = [];
    this.showError('');
    this.resetToInitialState();
  }



The output will be




And the validation is




I hope this small tutorial has helped you to create a simple Angular application to store the in-memory data,

Special thanks to bahurudeen for Bootstrap installation

The complete code is available at https://github.com/oneananda/ng-company-branch-crud


Happy Coding! 

Comments

Popular posts from this blog

Using of global variables in C# - Drawbacks & Solutions

How using global variables can have implications on the design, maintainability, and test-ability of C# code: Harder to understand and reason about the code:       class Program     {         public static int globalCounter = 0;         static void Main()         {             globalCounter++;             Console.WriteLine(globalCounter);         }     }   In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method. It's not clear where the value of the globalCounter is updated, it could be updated in other methods or classes, making it harder to trace the flow of data and understand the source of bugs.   More prone to errors:       class Program     {         public static string globalString;         static void Main()         {             globalString = "Hello" ;             Method1();             Method2();         }         static void Method1()         {

Task Parallel Library (TPL) and Akka.NET Alternatives

Task Parallel Library (TPL) and Akka.NET are among the most commonly used libraries for parallel and concurrent programming in the .NET ecosystem. However, there are also several other options available, depending on your specific needs: Parallel Language Integrated Query (PLINQ) is a parallel programming feature of .NET that provides an easy and efficient way to perform operations on collections in parallel. LINQ (Language Integrated Query) is a powerful feature in .NET that allows developers to work with data in a more declarative and language-integrated manner. While LINQ queries are inherently sequential, PLINQ extends LINQ by providing parallel versions of the query operators, allowing some queries to execute faster by utilizing multiple processors or cores on a machine. PLINQ is great when you are working with large collections where operations might be CPU-intensive or I/O-bound and could potentially be sped up by parallel execution. Here is a simple example of a PLI

SOLID Principles with Real World examples in C#

  SOLID Principles with Real World examples in C#   SOLID principles are formed by using S Single Responsibility Principles (SRP) O Open Closed Principle (OCP) L Liskov’s Substitution Principle (LCP) I Interface Segregation Principle (ISP) D Dependency Inversion Principle (DIP)   S Single Responsibility Principles (SRP) There should never be more than one reason for a class to change, to be precise one class should have only one responsibility Single Responsibility Principles (SRP) Real world example, A perfect match for SRP is Microservices , a Microservice will not contain functionalities other than the one it is designated to do,  Example ·                   Order Processing Service, ·                   Shipment Management Service, ·                   User Authentication Service, ·                   Catalogue List Service       class OrderProcessor     {         public void Process(Order order)         {             // Check inven