Angular CRUD Operation Using ASP.NET Core
When developing dynamic web applications, performing CRUD operations (Create, Read, Update, Delete) is a key feature for interacting with data. With Angular on the front end and ASP.NET Core on the back end, you can create a powerful, full-stack solution for handling CRUD operations efficiently. In this article, we will walk you through how to implement CRUD operations in Angular using ASP.NET Core to build modern web applications.
Why Use Angular and ASP.NET Core for CRUD Operations?
- Angular is a widely used JavaScript framework for building single-page applications (SPAs). It enables developers to create dynamic user interfaces that can communicate seamlessly with back-end services like ASP.NET Core.
- ASP.NET Core is a high-performance, open-source framework for building web APIs. It offers flexibility and cross-platform compatibility, making it an ideal choice for serving data to the front end, executing business logic, and interacting with databases.
By combining Angular and ASP.NET Core, developers can build highly scalable, robust, and responsive applications that enable users to perform CRUD operations effectively.
Setting Up the Development Environment
Before diving into the code, ensure that you have the following tools installed:
- Node.js (required for Angular development)
- Angular CLI (to create and manage Angular projects)
- Visual Studio (for creating ASP.NET Core projects)
- .NET SDK (to run ASP.NET Core applications)
- SQL Server (or another relational database) for data storage
Creating the ASP.NET Core API for CRUD Operations
Create a New ASP.NET Core Web API Project:
- Open Visual Studio and create a new project.
- Select ASP.NET Core Web Application and choose the API template.
- Name your project (e.g.,
CrudApi
), and click Create.
Create the Model:
You need a model that represents your data. For this example, let’s use a Product model.
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Stock { get; set; }
}
Create the Controller:
Create a controller that will handle the CRUD operations for the Product
model. The controller will expose HTTP endpoints that Angular will call to interact with the data.
[Route("api/[controller]")] [ApiController] public class ProductController : ControllerBase { private readonly ApplicationDbContext _context; public ProductController(ApplicationDbContext context) { _context = context; } // GET: api/product [HttpGet] public async Task<ActionResult<IEnumerable<Product>>> GetProducts() { return await _context.Products.ToListAsync(); } // GET: api/product/5 [HttpGet("{id}")] public async Task<ActionResult<Product>> GetProduct(int id) { var product = await _context.Products.FindAsync(id); if (product == null) { return NotFound(); } return product; } // POST: api/product [HttpPost] public async Task<ActionResult<Product>> PostProduct(Product product) { _context.Products.Add(product); await _context.SaveChangesAsync(); return CreatedAtAction("GetProduct", new { id = product.Id }, product); } // PUT: api/product/5 [HttpPut("{id}")] public async Task<IActionResult> PutProduct(int id, Product product) { if (id != product.Id) { return BadRequest(); } _context.Entry(product).State = EntityState.Modified; await _context.SaveChangesAsync(); return NoContent(); } // DELETE: api/product/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteProduct(int id) { var product = await _context.Products.FindAsync(id); if (product == null) { return NotFound(); } _context.Products.Remove(product); await _context.SaveChangesAsync(); return NoContent(); } }
This controller defines the CRUD operations for Product objects, including the Get, Post, Put, and Delete HTTP methods.
Creating the Angular Frontend
Now let’s create an Angular project to interact with the ASP.NET Core API.
Create a New Angular Project:
In your terminal, create a new Angular project:
ng new angular-crud
Install HttpClientModule:
You need to install the HttpClientModule to enable Angular to make HTTP requests. Open app.module.ts
and import HttpClientModule:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Angular Service for CRUD Operations
Create a service that will handle the HTTP requests to interact with the ASP.NET Core API.
Create Product Service (product.service.ts):import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Product } from './product'; @Injectable({ providedIn: 'root' }) export class ProductService { private apiUrl = 'https://localhost:5001/api/product'; // ASP.NET Core API URL constructor(private http: HttpClient) {} getProducts(): Observable<Product[]> { return this.http.get<Product[]>(this.apiUrl); } getProduct(id: number): Observable<Product> { return this.http.get<Product>(`${this.apiUrl}/${id}`); } addProduct(product: Product): Observable<Product> { return this.http.post<Product>(this.apiUrl, product); } updateProduct(product: Product): Observable<void> { return this.http.put<void>(`${this.apiUrl}/${product.id}`, product); } deleteProduct(id: number): Observable<void> { return this.http.delete<void>(`${this.apiUrl}/${id}`); } }
This service includes methods to fetch data from the backend (using GET), add new data (using POST), update data (using PUT), and delete data (using DELETE).
Creating the Angular Component for Product List
Create a component to display the list of products and perform CRUD operations.
Product List Component (product-list.component.ts):import { Component, OnInit } from '@angular/core';
import { ProductService } from './product.service';
import { Product } from './product';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
products: Product[];
constructor(private productService: ProductService) {}
ngOnInit(): void {
this.loadProducts();
}
loadProducts(): void {
this.productService.getProducts().subscribe(data => {
this.products = data;
});
}
deleteProduct(id: number): void {
this.productService.deleteProduct(id).subscribe(() => {
this.loadProducts();
});
}
}
<table> <thead> <tr> <th>Name</th> <th>Price</th> <th>Stock</th> <th>Actions</th> </tr> </thead> <tbody> <tr *ngFor="let product of products"> <td>{{ product.name }}</td> <td>{{ product.price }}</td> <td>{{ product.stock }}</td> <td> <button (click)="deleteProduct(product.id)">Delete</button> </td> </tr> </tbody> </table>
Conclusion
Integrating Angular with ASP.NET Core for CRUD operations allows you to create dynamic and responsive full-stack web applications. By following this guide, you have learned how to implement Create, Read, Update, and Delete functionality, enabling users to interact with the backend seamlessly. Whether you're building a small project or a large enterprise application, this full-stack approach will serve as a solid foundation for your web development needs.