Building A CRUD Application In Angular

Building A CRUD Application In Angular

Angular, a type-script based open-source single-web application framework developed by Google has gain its popularity in web application in a very short span. It was released on 14th Sept, 2016 and now it is the most used front-end framework for web applications.

In this article, we will build a CRUD — Create, Read, Update, Delete application using Angular. The application will have the following features.

  1. A main component to display data and perform CRUD operations.
  2. A service to handle data storage.
  3. Separate components for adding and editing items.

Prerequisites

Step — 1: Install Angular CLI

Let’s install Angular CLI in order to work with Angular Components.

Create a folder in the location of your choice and open command prompt. (In some cases you might need to open it as Administrator if you don’t have enough permissions to write in that folder)

Visit the link to copy the CLI command or straightaway use the following command to get started.

npm i @angular/cli        

Step — 2: Create A New Angular App

Once Angular CLI is successfully installed, we are now ready to create a brand new app in angular.

Remember, the new versions of Angular apps would create Standalone applications by default. We would not be creating it as of now just to maintain the simplicity as we are learning the work of Angular framework in action.

Type the following command in your command prompt:

Notice, there is a flag called — standalone which is set to false, meaning we don’t wish to create standalone application in this demonstration.

It will ask you to select the stylesheet format. Just press Enter and resume the process:

Next, it will ask you to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering), press “y” and then Enter.

As soon as you press enter, it will install necessary files and modules. This process will take some time. Once done, you will get a success message.

If you get any error while installing, you can simply run npm install` to install all the necessary packages. This will update the new ones and install the missing ones. It would look something like this:

It’s now time to navigate to our project folder by simply typing

This is the project folder directory that we would be using most of the time.

Open the application in Visual Studio Code typing code .

This will open your Visual Studio Code (VS Code) for you:

Serve the application!

To see how the initial Angular application looks like, you can type ng serve.

This will generate a browser navigable URL which you can copy in to your browser and see the output.

If it asks you to share the data with Google, press ’N’ and Enter key to resume the process.
The default port for Angular Application on which it will be served is 4200

Initial Output:

Step — 3: Create Components

For our CRUD application, we will create few components which will be served as building blocks of our Angular application.

We will create two components: one for adding products name it as product-form, followed by another component for displaying data product-list.

Once they are created, you’ll see the success output:

Step — 4: Create The Service

Open another command prompt with same location, and type the following command in it and press Enter:

Open the src/app` folder to find our product service that we just created.

Step — 5: Add the Interface In Product Service

In your Product Service component, we will add an interface to act it as a Model in our Angular application. That product interface would contain simple three fields: id, name, description

Step — 6: Read All Products

In order to retrieve all our products, we will create a method which will get all the products.

Explanation

  • We’ve declared a variable products` of type Product Interface. This will hold our data. We have added some dummy data for demonstration purpose. In real life, this data would come from your database.
  • In the next step we have kept created method getProducts(). This returns all the products available in the array of Products.

Step — 7: Product List Component

Open your product-list.component.ts` component and write the following code in it.

Explanation

  • We have created an array of Products to access it in our HTML markup page.
  • The ProductListComponent contains a constructor that will be used to inject the services to use the methods within it.
  • The ngOnInit() method is one of the methods of Angular Life Cycle that runs when the page loads. In this method, we have accessed the getProducts() of product service and assigned it to the array of products.

Step — 8: Modify the Product List Component HTML

In order to show the data on our browser, modify your product-list.component.html file with the following HTML markup.

Explanation:

  • It contains a normal <ul> tag and <li> tag.
  • The <li>` tag contains *ngFor` directive which is a special directive in Angular to loop through the given array. It loops through products` and each product is accessed by its name and description.

Output:

This is how our first fetch products functionality looks like:

Step — 9: Create/Edit Products

This component contains the form used for both adding and editing products.

Open your product-form.component.ts. And include the following code in your component:

Explanation:

  • The ProductFormComponent` implements OnChanges` method of Angular life cycle to track what change need to be done when the page state changes.
  • We have added few @Input and @Output. directives. The Input one is used to pass the data from parent component to child component and the Output one is used to pass from child to parent component.
  • There is ngOnChanges()` that takes the changes occurred in the Angular page and assigns it to the array of product to display it on the page.
  • The onSave() is used to trigger the save functionality of the product. The emit()` would emit the data from product-form` (which acts as child component) to product-list` component (which acts as parent component). This is the method is due to Output directive declared.
  • The onCancel()` cancels the form submission (i.e. creation of products or edit)

Step — 10 : Modify the Product Form Component HTML

It’s now time to modify the HTML component of the Product Form to add some data.

Explanation

  • We have two buttons for Edit or Add Products
  • A form with onSave()`. This will get all the inputs within that form and send it to the save event. Which will be then handled by our service (which we will creating shortly).
  • Created few simple UI to display the name and description textboxes to add the data.
  • Added Save button and Cancel button.

If you get any error on ngModel, it means your project misses “FormsModule”. We can add it in app.module.ts file.

Step — 11: Modify the Product List Component

In this we will modify the product-list.component.html` to include our product-form.component.html`.


Explanation

  • The [product] is the one way binding that doesn’t expect any product in return. This will be just for the selection purpose.
  • The save() and cancel() are two events to submit the data and/or cancel the operation respectively.

Initially you’ll get errors as these variables are not present in product list components. So let’s create them now. Open your product-list.component.ts.


Explanation

  • It contains three methods edit, save and cancel
  • Each method calls the service and the dedicated method in it.

If you get errors here as well, don’t worry, we would sort it out. In order to sort the errors, add those errors in your services as well.

Open your product.service.ts and modify that file with the highlighted code below:


With all these methods, your components should stop complaining. We have added the Add and Update method as we will be performing both the methods on the same component.

Output:

Try to access your component and you will see a form to add the products:


Try adding some products from that form and see if that adds up to the above list.


After clicking Save` button:


Hurray!! We’ve been doing so good so far ??

If you click cancel, the current operation will be suspended and the data won’t be posted. Which means, you won’t be able to see it on the list. Try that out on your own! ??

Add Edit button after every list to edit the functionality


We’ve already added the Edit functionality. Try to click the Edit button and see what happens

Output:

Before clicking Edit button:

Click on Edit of any product list and see what happens:


You would see the corresponding data has filled into our Product form component controls. Try to update the data and save it!


I have updated the name of the product. The Headphones has been updated to Updated Headphones.

Step — 12: Deleting The Product

First we will modify our service to include the deletion process method.

Next, modify our product-list.component.ts` to handle the delete functionality and send the request to the service:


And finally, modify your product-list.component.html` to include Delete button to remove any product from the list. Here’s the code:


Output:


After clicking Delete of any product from the list:


Did you find any product missing? It’s because I’ve hit delete to remove it from our list.

Summary

  1. Data Handling: The ProductService contains all CRUD methods.
  2. Item List and Form: ProductListComponent displays products and has controls for each operation. ProductFormComponent handles adding and editing items.
  3. One-Page CRUD: All operations are available within ProductListComponent without additional navigation.

This example demonstrates a simple, efficient CRUD application in Angular, with each operation handled directly on the main page.

Thanks for reading! ??


要查看或添加评论,请登录

Rohan Rao的更多文章

  • Top 10 Tricks to Master JavaScript

    Top 10 Tricks to Master JavaScript

    When it comes to the most powerful and versatile programming languages in the world, especially for web development…

    2 条评论
  • Top 15 JS Useful Array Methods

    Top 15 JS Useful Array Methods

    JavaScript is a very popular scripting, single-threaded, dynamic, object-oriented language used to create interactive…

  • Data Analysis In Python

    Data Analysis In Python

    Data has been an integral part of business in their day-to-day operations to keep track and derive insights from it…

社区洞察

其他会员也浏览了