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

Task Parallel Library (TPL) and Akka.NET: Differences

Task Parallel Library (TPL) and Akka.NET are both powerful tools in the .NET ecosystem for handling parallelism and concurrency, but they serve different purposes and use different models of computation. Here are some key differences:s 1.    Actor Model vs Task-Based Model: Akka.NET is built around the actor model, where actors are the fundamental units of computation and they communicate by exchanging messages. TPL, on the other hand, is task-based. It's designed to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. TPL uses tasks (which are independently executing work units) and provides various ways to control and coordinate them. 2.    Fault Tolerance: One of the key features of Akka.NET is its built-in fault tolerance. It has a "let-it-crash" philosophy, where the system is designed to self-heal from errors. If an actor fails, its parent actor can decide on the supervision strategy: either to resta

Extension Methods - Advanced

Here we will see how can we use the Extension Methods in advanced manner in other types Imagine you often need to retrieve items from a List based on a custom criterion that the built-in LINQ methods don't cover. Extension Methods for Lists: Filtering based on Custom Criteria And the output would be   Extending Enums: Displaying Descriptive Strings Output: Extending DateTime: Calculating Age     Output: The code samples can be found at https://github.com/oneananda/C_Sharp_Examples/tree/main/ExtensionMethods