Spring Boot + Angular 12 CRUD Operations Example(2023) | CodeUsingJava


































Spring Boot + Angular 12 CRUD Operations Example(2023)

In the previous tutorial, we had implemented a hello world program using Angular and Spring boot.
Now, In this article, I would be implementing other endpoints i.e. create and delete customers using angular and Spring Boot.
At last, we would be using a Header and Footer in our angular applications.
The structure of the program would be as follows-
Application Structure

Spring Boot Project Structure

This will be the standard directory layout for maven project structure-
Spring Boot Maven Project

Now we modify the controller class for the application as follows-
We declare the customerList before the methods and also added the restendpoints for delete as well as creating the customers from the list.
	package com.codeusingjava.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.codeusingjava.model.Customers;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class HelloController {
	
	List <Customers> customerList = new ArrayList<Customers>();
	
	@RequestMapping(value = "/Customers", method = RequestMethod.GET)
	public List <Customers> test(Model model) {	
//		customerList.add(new Customers("abc", "xyz" ));
//		customerList.add(new Customers("a2", "b2" ));
//		
		return customerList;
	}
	
	
	@DeleteMapping(path = { "/{name}" })
	public Customers delete(@PathVariable("name") String name) {
		Customers deletedCust = null;
		for (Customers cust : customerList) {
			if (cust.getFirstName().equals(name)) {
				customerList.remove(cust);
				deletedCust = cust;
				break;
			}
		}
		return deletedCust;
	}

	@PostMapping("/addCustomers")
	public Customers create(@RequestBody Customers cust) {
		customerList.add(cust);
		System.out.println(customerList);
		return cust;
	}
}

Angular Project Structure

The updated project structure for the Angular crud operations is as follows-
angular project str
 
	import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export class Customers{
  constructor(
    public firstName:string,
    public lastName:string,
  ) {}
}

@Injectable({
  providedIn: 'root'
})
export class HttpClientService {

  constructor(
    private httpClient:HttpClient
  ) { 
     }

     getCustomers()
  {
    console.log("test call");
    return this.httpClient.get<Customers[]>('http://localhost:8080/Customers');
  }
  public deleteCustomers(customer: Customers) {
	return this.httpClient.delete<Customers>("http://localhost:8080" + "/"+ customer.firstName);
  }
  
  public createCustomers(customer: Customers) {
	return this.httpClient.post<Customers>("http://localhost:8080/addCustomers", customer);
  }
}

To provide the styles to our file, we add the bootstrap.css url inside the style.css file:
The global styles can be used in this file.
 
	@import url(https://unpkg.com/bootstrap@4.1.0/dist/css/bootstrap.min.css)
Inside the Customers Component, we add the functionality for deleting the customer:-
 
	import { Component, OnInit } from '@angular/core';
	import { Customers, HttpClientService } from '../service/http-client.service';
	
	@Component({
	  selector: 'app-customers',
	  templateUrl: './customers.component.html',
	  styleUrls: ['./customers.component.css']
	})
	export class CustomersComponent implements OnInit {
	   customers:Customers[] = [];
	
	  constructor(
		private httpClientService:HttpClientService
	  ) { }
	
	  ngOnInit() {
		this.httpClientService.getCustomers().subscribe(
		 response =>{this.customers=response;},
		);
	  } 

	deleteCustomers(customer: Customers): void {
		this.httpClientService.deleteCustomers(customer)
		  .subscribe( data => {
			this.customers = this.customers.filter(u => u !== customer);
		  })
	  };
	}	
Inside the app.module.ts, we add the HttpClientModule to app.module.ts
 
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomersComponent } from './customers/customers.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomersComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule  
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Inside the customer component html file, we need to add the button for deleting the customer:-
 
<table border="1">
    <thead></thead>
    <tr>
      <th>firstName</th>
      <th>lastName</th>
      </tr>
    
    <tbody>
        <tr *ngFor="let cust of customers">
            <td>{{cust.firstName}}</td>
			<td>{{cust.lastName}}</td>
			<td><button class="btn btn-danger" (click)="deleteCustomers(cust)"> Delete Customer</button></td>
           
            </tr>
    </tbody>
      </table>

delete module

Adding the Customer

Firstly we generate the component for adding the customer using the command ng generate component add-customer.
For this, we need to create a form to add the customers:
Inside the add customers component.ts file, we write method for creating the file:
 
	import { Component, OnInit } from '@angular/core';
import { Customers, HttpClientService } from '../service/http-client.service';

@Component({
  selector: 'app-add-customer',
  templateUrl: './add-customer.component.html',
  styleUrls: ['./add-customer.component.css']
})
export class AddCustomerComponent implements OnInit {
  cust: Customers = new Customers("","");

  constructor(
    private httpClientService: HttpClientService
  ) { }

  ngOnInit(): void {
  }

createCustomers(): void {
    this.httpClientService.createCustomers(this.cust)
        .subscribe( data => {
          alert("Customer added to the list successfully.");
        });
};
}


Inside the add-customer component.html file, we create a form:-
Here we are using the ngModel directives:-
 
	<div class="col-md-6">
  <h2 class="text-center">Add Customer</h2>
  <form>
    <div class="form-group">
      <label for="name">FirstName:</label>
      <input [(ngModel)]="cust.firstName" placeholder="FirstName" name="firstName" class="form-control" id="firstName">
    </div>
  
     <div class="form-group">
      <label for="lastname">LastName:</label>
      <input [(ngModel)]="cust.lastName" placeholder="LastName" name="lastName" class="form-control" id="lastName">
    </div>
  
   
    <button class="btn btn-success" (click)="createCustomers()">Create</button>
  </form>
  </div>

As mentioned above, ngModel directives are used, So we need to add the FormsModule in the app.module.ts file, else exception is thrown:
 
	import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomersComponent } from './customers/customers.component';
 import { AddCustomerComponent } from './add-customer/add-customer.component';
 import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomersComponent,
     AddCustomerComponent,
     HeaderComponent,
     FooterComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


There is also need of routing at the app.routing.ts file the add-customer component.
 
	import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddCustomerComponent } from './add-customer/add-customer.component';
import { CustomersComponent } from './customers/customers.component';

const routes: Routes = [
  { path:'', component: CustomersComponent},
  { path:'addCustomers', component: AddCustomerComponent},

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

The Add-customer form is displayed at localhost:4200/addCustomers
angular add customers

angular added customers

Header Component

We can create a header in our application. For these, we generate a header component as follows-
header
We create the header-component.html as follows-
 
	<header>
    <nav class ="navbar navbar-expand-md navbar-dark bg-dark">
    <div><a href="https://www.javainuse.com" class="navbar-brand">CodeUsingJava</a></div>
    
    <ul class="navbar-nav">
      <li><a  routerLink="/" class="nav-link">View Customers</a></li>
      <li><a  routerLink="/addCustomers" class="nav-link">Add New Customers</a></li>
    
    </ul>
    
    </nav>
    </header>

Header Component

We can create a footer in our application. For these, we generate a footer component as follows-
footer
We create the footer-component.html as follows-
 
	<footer class="footer">
    <div class="container">
        <span class="text-muted">All Rights Reserved @CodeUsingJava</span>
    </div>
  
  </footer>
When we run the program, we get the output as follows-
angular final output

Downloads-

Angular Code
Spring Boot Code