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,
Create an Angular 5 project by executing commands as described below.
To create a new Angular project:
After creating a project, we need to install a dependency,
Now, our application is ready to run, just execute the following command:
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 a 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:
- <div class="container" style="margin-top: 15px;text-align: -webkit-center;">
- <div class="panel panel-default" style="width: 70%;text-align: -webkit-center;">
-
- <!-- This is panel Heading -->
- <div class="panel-heading" style="text-align:center">
- <h3>Working With Array In Angular 5</h3>
- </div>
-
- <!-- This is panel Body -->
- <div class="panel-body" style="text-align: -webkit-center;">
- </div>
-
- <!-- This is panel footer -->
- <div class="panel-footer">
- <div class="form-group">
- <!-- Form that gets user input -->
- <form name="itemForm">
- <input id="Value" name="Value" required minlength="3" maxlength="15" style="width: 50%;" placeholder="Enter Any Item"
- class="form-control">
- </form>
- <br>
- <!-- Add button to add record -->
- <button type="submit" class="btn btn-default">Add</button>
- <!-- Update button to submit updated value -->
- <button type="submit" class="btn btn-default">Update</button>
- </div>
- </div>
-
- </div>
- </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,
- import {Component, OnInit } from '@angular/core';
-
- export class MyItems {
- Value: string;
- constructor(Value:string)
- {
- this.Value = Value;
- }
- }
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
-
-
- title = 'Working With Array In Angular 5';
-
-
- myItems: MyItems[] = new Array();
-
-
- IsForUpdate: boolean = false;
- newItem: any = {};
- updatedItem;
-
-
- constructor()
- {
- this.myItems.push(
- new MyItems("First Value"),
- new MyItems("Second Value"),
- new MyItems("Third Value"),
- new MyItems("Forth Value"),
- new MyItems("Fifth Value")
- );
- }
- }
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:
- <div class="panel-body" style="text-align: -webkit-center;">
- <div *ngFor="let data of myItems;let i= index" class="alert alert-info" style="width: 50%;">
- {{data.Value}}
- <a href="#" style="float: right;">
- <span class="glyphicon glyphicon-remove"></span>
- </a>
- <a href="#" style="float: right;padding-right: 8px;">
- <span class="glyphicon glyphicon-pencil"></span>
- </a>
- </div>
- <div *ngIf="myItems.length == 0" class="alert alert-info" style="width: 50%;">
- Items Are Empty !!!
- </div>
- </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,
-
- AddItem() {
- this.myItems.push(
- this.newItem
- );
- this.newItem = {};
- }
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,
- <!-- This is panel footer -->
- <div class="panel-footer">
- <div class="form-group">
- <!-- Form that gets user input -->
- <form name="itemForm">
- <input id="Value" name="Value" required [(ngModel)]="newItem.Value" minlength="3" maxlength="10" style="width: 50%;" placeholder="Enter Any Item"
- class="form-control">
- </form>
- <br>
- <!-- Add button to add record -->
- <button type="submit" (click)="AddItem()" [disabled]="IsForUpdate == true" class="btn btn-default">Add</button>
- <!-- Update button to submit updated value -->
- <button type="submit" class="btn btn-default">Update</button>
- </div>
- </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,
-
- EditItem(i) {
- this.newItem.Value = this.myItems[i].Value;
- this.updatedItem = i;
- this.IsForUpdate = true;
- }
-
-
- UpdateItem() {
- let data = this.updatedItem;
- for (let i = 0; i < this.myItems.length; i++) {
- if (i == data) {
- this.myItems[i].Value = this.newItem.Value;
- }
- }
- this.IsForUpdate = false;
- this.newItem = {};
- }
Explanation
For editing specific records, and after updating value, there are two separate methods that perform different functions.
- EditItem - Selects the specific user for the edit.
- 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:
- <!-- This is panel Body -->
- <div class="panel-body" style="text-align: -webkit-center;">
- <div *ngFor="let data of myItems;let i= index" class="alert alert-info" style="width: 50%;">
- {{data.Value}}
- <a href="#" (click)="DeleteItem(i)" style="float: right;">
- <span class="glyphicon glyphicon-remove"></span>
- </a>
- <a href="#" (click)="EditItem(i)" style="float: right;padding-right: 8px;">
- <span class="glyphicon glyphicon-pencil"></span>
- </a>
- </div>
- <div *ngIf="myItems.length == 0" class="alert alert-info" style="width: 50%;">
- Items Are Empty !!!
- </div>
- </div>
And for binding UpdateItem() method to button we need to modify app.component.html like,
- <!-- Update button to submit updated value -->
- <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:
-
- DeleteItem(i) {
- this.myItems.splice(i, 1);
- }
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 a 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 the 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.