CRUD Using Array In Angular 5

Introduction
 
In this article, on Angular, we are going to see how to do CRUD operations using an array in Angular 5.
 
I found many articles showing CRUD operations with Angular in many different ways, but I chose a simple way to do the same task with an array so that beginners can create and learn simple methods for CRUD operations.
 
An array is a great way to do CRUD operations without using any kind of storage. 
 
Let's start by implementing the demo step-by-step.
 
You will get output after the completion of this tutorial :
 


Step  1.
 
Create Angular 5 project by executing commands as described below. 
 
To create a new Angular project:
  1. ng new  crudangular5array  
After creating a project, we need to install a dependency,
  1. npm install  
Now, our application is ready to run, just execute the following command:
  1. ng serve -o  
After completion of all the above steps, a new window will open in the browser and you can see the default output for the project.
  
Step 2. 

So far, we have created and executed an application with predefined structure.
 
It's time to customize files as per our CRUD operation requirements.
 
I'm going to customize the layout of our single page application, and add some bootstrap components to accept user input and process it
 
Open app.component.html and paste the given snippet: 
  1. <div class="container" style="margin-top: 15px;text-align: -webkit-center;">    
  2.   <div class="panel panel-default" style="width: 70%;text-align: -webkit-center;">    
  3.     
  4.     <!-- This is panel Heading -->    
  5.     <div class="panel-heading" style="text-align:center">    
  6.       <h3>Working With Array In Angular 5</h3>    
  7.     </div>    
  8.     
  9.     <!-- This is panel Body -->    
  10.     <div class="panel-body" style="text-align: -webkit-center;">    
  11.     </div>    
  12.     
  13.     <!-- This is panel footer -->    
  14.     <div class="panel-footer">    
  15.       <div class="form-group">    
  16.         <!-- Form that gets user input -->    
  17.         <form name="itemForm">    
  18.           <input id="Value" name="Value" required  minlength="3" maxlength="15" style="width: 50%;" placeholder="Enter Any Item"    
  19.             class="form-control">    
  20.         </form>    
  21.         <br>    
  22.         <!-- Add button to add record -->    
  23.         <button type="submit"  class="btn btn-default">Add</button>    
  24.         <!-- Update button to submit updated value -->    
  25.         <button type="submit"  class="btn btn-default">Update</button>    
  26.       </div>    
  27.     </div>    
  28.     
  29.   </div>    
  30. </div>   
After executing, you can see the simple layout as below :
 
 
 
As you can see in the above screen, it contains a simple bootstrap panel with its header, body, and footer part with textbox and buttons.
 
It's just a normal HTML page, with the form not working completely, soon we will make it dynamic.
 
Step 3.
 
Now, we are going to start with CRUD operations with Array.
 
For that, I am modifying component snippet and creating necessary variables as below,
  1. import {Component, OnInit } from '@angular/core';    
  2.     
  3. export class MyItems {    
  4.   Value: string;    
  5.   constructor(Value:string)    
  6.   {    
  7.     this.Value = Value;    
  8.   }    
  9. }    
  10.     
  11. @Component({    
  12.   selector: 'app-root',    
  13.   templateUrl: './app.component.html',    
  14.   styleUrls: ['./app.component.css']    
  15. })    
  16. export class AppComponent  {    
  17.     
  18.   // Used To Specify Title using Interpolation    
  19.   title = 'Working With Array In Angular 5';    
  20.     
  21.   // Array where we are going to do CRUD operations    
  22.   myItems: MyItems[] = new Array();    
  23.     
  24.   // Other variables    
  25.   IsForUpdate: boolean = false;    
  26.   newItem: any = {};    
  27.   updatedItem;    
  28.     
  29.   // Provide some values to the array    
  30.   constructor()    
  31.   {    
  32.     this.myItems.push(    
  33.       new MyItems("First Value"),    
  34.       new MyItems("Second Value"),    
  35.       new MyItems("Third Value"),    
  36.       new MyItems("Forth Value"),    
  37.       new MyItems("Fifth Value")    
  38.     );    
  39.   }     
  40. }    
Explanation
 
I created a class named MyItems that is used to store items in an array.
 
And also, created a myItems array that uses a class to add items to it. Here, I'm providing a few default items to my array.
 
To print items of Array, we need to modify our app.component.html file.
 
Just replace the below lines of code with panel-body section like this: 
  1. <div class="panel-body" style="text-align: -webkit-center;">    
  2.       <div *ngFor="let data of myItems;let i= index" class="alert alert-info" style="width: 50%;">    
  3.         {{data.Value}}    
  4.         <a href="#" style="float: right;">    
  5.           <span class="glyphicon glyphicon-remove"></span>    
  6.         </a>    
  7.         <a href="#" style="float: right;padding-right: 8px;">    
  8.           <span class="glyphicon glyphicon-pencil"></span>    
  9.         </a>    
  10.       </div>    
  11.       <div *ngIf="myItems.length == 0" class="alert alert-info" style="width: 50%;">    
  12.         Items Are Empty !!!    
  13.       </div>    
  14. </div>      
Here, I have used [ *ngFor = " " ] to print items of array, and if array will be empty than you can get message from Items that are empty by default. 
 
Let's execute our app, and you can see the output like the below screen:
 
 
 
We have created Select operation for CRUD, now it's time to add a new record. 
 
Step 4. 
 
Let's implement the functionality to add a new item to the array, for that we are going to create a new method in a component class and binding click event in ADD button click event.
 
app.component.ts
 
Open file and add new method inside component class,
  1. // To add new item in array    
  2.  AddItem() {    
  3.    this.myItems.push(    
  4.      this.newItem    
  5.    );    
  6.    this.newItem = {};    
  7.  }    
Here, we are going to use two-way data binding with "newItem", which binds textbox value automatically .
 
For that, within HTML, I'm going to use [(ngModel)]="" to work with two-way data binding.
 
To get an idea about how two-way data binding works you can refer to the below link,
app.component.html
 
Open HTML and replace the panel-footer snippet, that we have previously created,
  1. <!-- This is panel footer -->      
  2.   <div class="panel-footer">      
  3.     <div class="form-group">      
  4.       <!-- Form that gets user input -->      
  5.       <form name="itemForm">      
  6.         <input id="Value" name="Value" required [(ngModel)]="newItem.Value" minlength="3" maxlength="10" style="width: 50%;" placeholder="Enter Any Item"      
  7.           class="form-control">      
  8.       </form>      
  9.       <br>      
  10.       <!-- Add button to add record -->      
  11.       <button type="submit" (click)="AddItem()" [disabled]="IsForUpdate == true" class="btn btn-default">Add</button>      
  12.       <!-- Update button to submit updated value -->      
  13.       <button type="submit" class="btn btn-default">Update</button>      
  14.     </div>      
  15.   </div>        
As you can see, within ADD button (click)=" " event is bound to add new item into the array using component code with the value of  [(ngModel)]="newItem.Value"
 
Now, its time to add new item and check the output:
 
 
 
We added one item which shows inside panel-body, which lists down array items automatically when we modify any records or try to add new records.
 
We have created functionality for SELECT and ADD new records, now, let' move to update operation in crud operations.
 
Step 5.
 
We are going to modify record which we already added to the array, for that, I've added one method which takes a record that needs to be updated.
 
Open app.component.ts file and add the following method,
  1. // When user selects edit option  
  2. EditItem(i) {  
  3.   this.newItem.Value = this.myItems[i].Value;  
  4.   this.updatedItem = i;  
  5.   this.IsForUpdate = true;  
  6. }  
  7.   
  8. // When user clicks on update button to submit updated value  
  9. UpdateItem() {  
  10.   let data = this.updatedItem;  
  11.   for (let i = 0; i < this.myItems.length; i++) {  
  12.     if (i == data) {  
  13.       this.myItems[i].Value = this.newItem.Value;  
  14.     }  
  15.   }  
  16.   this.IsForUpdate = false;  
  17.   this.newItem = {};  
  18. }  
Explanation
 
For editing specific records, and after updating value, there are two separate methods that perform different functions.
  1. EditItem - Selects the specific that user wants to update 
  2. UpdateItem - After modifying a record, we need to update value to the array.
app.component.html
 
We need to bind this event to buttons so that we can get specific records and also can update them. 
 
So, the final snippet of panel-body will be like this: 
  1. <!-- This is panel Body -->  
  2.     <div class="panel-body" style="text-align: -webkit-center;">  
  3.        <div *ngFor="let data of myItems;let i= index" class="alert alert-info" style="width: 50%;">  
  4.          {{data.Value}}  
  5.          <a href="#" (click)="DeleteItem(i)" style="float: right;">  
  6.            <span class="glyphicon glyphicon-remove"></span>  
  7.          </a>  
  8.          <a href="#" (click)="EditItem(i)" style="float: right;padding-right: 8px;">  
  9.            <span class="glyphicon glyphicon-pencil"></span>  
  10.          </a>  
  11.        </div>  
  12.        <div *ngIf="myItems.length == 0" class="alert alert-info" style="width: 50%;">  
  13.          Items Are Empty !!!  
  14.        </div>  
  15.      </div>  
And for binding UpdateItem() method to button we need to modify app.component.html like,
  1. <!-- Update button to submit updated value -->    
  2.        <button type="submit" (click)="UpdateItem()" [disabled]="IsForUpdate == false" class="btn btn-default">Update</button>   
 
For editing record, we need to select any record and for that, I've used two links with an icon and bound events, that we created previously.
 
After executing an application, I have selected one record and modified its text like this:
 
 
 So, In this way we can update our record, the last step is to delete any record.
 
Step 6.
 
At last, we just need to add method for delete operation inside component as below:
  1. // To delete specific item  
  2. DeleteItem(i) {  
  3.   this.myItems.splice(i, 1);  
  4. }  
Let's run this and delete any record:
 
 
After delete operation , you can see array item will be deleted.
 
So far we have created all the operations for CRUD operations step-by-step.
 
Conclusion  
 
In this part of the Angular tutorial, we have seen a simple way to create CRUD operation using an array.
 
Keep in mind that it does not follow any coding standard, because its just a demonstration, you can modify this demo as per your requirement and can use coding proper standards. 
 
Download attached project and try to execute by yourself, let me know if you face any issue. 
 
To follow my other articles on Angular just go through the below links :
I hope you have learned something from this tutorial. Thanks for reading. 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now