Form Handling in Angular and Spring Boot – Complete Full Stack Application Guide

Form Handling in Angular and Spring Boot – Complete Full Stack Application Guide

Overview

In this tutorial, you’ll learn how to build a complete full stack application using Angular for the frontend and Spring Boot for the backend, with a focus on form handling and API integration. This guide covers everything from creating and managing forms in Angular to saving the form data into a MySQL database using Spring Boot REST APIs.

Form Handling in Angular and Spring Boot

Table of Contents:

  • Setting Up Angular Project
  • Creating and Handling the Form in Angular
  • Creating Spring Boot Application (Backend)
  • Configuring application.properties.
  • Creating Entity, Repository, Service, Controller
  • Fixing CORS Issues
  • Connecting Angular with Spring Boot API

Now let’s understand how we can create form and handle it in Angular and Spring Boot. Create Complete full-stack web application using angular and spring boot

Step 1: Setting Up the Angular Application

First, create your Angular project using Angular CLI:

ng new angular-form-app  

Navigate into your project directory:

cd angular-form-app 

Start the development server and check application running or not:

ng serve

Step 2: Creating and Handling the Form in Angular

Generate a new component:

ng generate component user-form 

HTML Template (user-form.component.html)


<h2>User Registration Form</h2>

<form (ngSubmit)="onSubmit()" #userForm="ngForm">
  <input type="text" name="firstName" [(ngModel)]="user.firstName" placeholder="First Name" required />
  <br /><br />
  
  <input type="text" name="lastName" [(ngModel)]="user.lastName" placeholder="Last Name" required />
  <br /><br />
  
  <input type="email" name="email" [(ngModel)]="user.email" placeholder="Email" required />
  <br /><br />
  
  <input type="tel" name="phone" [(ngModel)]="user.phone" placeholder="Phone Number" />
  <br /><br />
  
  <input type="text" name="city" [(ngModel)]="user.city" placeholder="City" />
  <br /><br />
  
  <input type="text" name="country" [(ngModel)]="user.country" placeholder="Country" />
  <br /><br />
  
  <button type="submit">Submit</button>
</form>

✔ Component Logic (user-form.component.ts)


import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-user-form',
  templateUrl: './user-form.component.html'
})
export class UserFormComponent {
  user = {
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    city: '',
    country: ''
  };

  constructor(private http: HttpClient) {}

  onSubmit() {
    this.http.post('http://localhost:8080/api/users', this.user)
      .subscribe(response => {
        console.log('User data saved successfully:', response);
        alert('Form submitted successfully!');
      });
  }
}

✔ Add FormsModule and HttpClientModule to app.module.ts


import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    FormsModule,
    HttpClientModule
  ]
})
export class AppModule {}

Step 3: Setting Up Spring Boot (Backend)

Create a new Spring Boot project using Spring Initializr or your IDE with the following dependencies:

  • Spring Web
  • Spring Data JPA
  • MySQL Driver

Step 4: Configure application.properties


server.port=8080

spring.datasource.url=jdbc:mysql://localhost:3306/angular_db
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
        

For More Details:

If you want to learn more about configuring the application.properties file, check out this detailed article:

Create REST APIs Using Spring Boot: Step-by-Step Guide

Step 5 : Creating the Entity, Repository, Service and Controller for our API

Entity Class (UserData)


@Entity
public class UserData {

    private String firstName;
    private String lastName;

    @Id
    private String email;

    private String contactNumber;
    private String address;
    private String city;
    private String state;
    private String country;

    // Parameterized constructor
    public UserData(String firstName, String lastName, String email, 
                      String contactNumber, String address, 
                      String city, String state, String country) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.contactNumber = contactNumber;
        this.address = address;
        this.city = city;
        this.state = state;
        this.country = country;
    }

    // Non-parameterized constructor
    public UserData() {
    }

    // Getters and Setters

}

Repository


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.crudAPI.example.entity.Students;

@Repository
public interface StudentRepo extends JpaRepository<Students, Integer> {

}

Service


@Service
public class UserDataService {

    @Autowired
    private UserDataRepository userDataRepository;

    public UserData save(UserData userData) {
        return userDataRepository.save(userData);
    }
}

Controller (for defining api endpoint)


@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:4200")
public class UserDataController {

    @Autowired
    private UserDataService userDataService;

    @PostMapping("/saveUserData")
    @CrossOrigin(origins = "http://localhost:3000")
    public UserData save(@RequestBody UserData userData) {
        return userDataService.save(userData);
    }
}

Project Structure

Here’s an image showing project for our spring boot application

spring boot project structure for CRUD APIs

Run the Application

Run your Spring Boot application. It will automatically create the table in your database based on the UserData entity.

automatic table created

Step 6: Connect Angular and Spring Boot

Make sure your Angular app is running on port 4200 and Spring Boot is on port 8080. Use the full endpoint http://localhost:8080/api/users in Angular to make POST requests.

Angular runs on port 4200, Spring Boot on 8080, so you must enable CORS to avoid errors: Add @CrossOrigin(origins = "http://localhost:4200") in the controller to allow CORS.

📦 Final Output

  1. Start your Spring Boot app:
    Run UserFormApplication.java
  2. Start Angular frontend:
    Run ng serve
  3. Submit the Form:
    Fill out the form → Click Submit → Data is saved in MySQL → Success message shown in the UI.

Key Concepts Covered

  • Two-Way Data Binding in Angular using [(ngModel)]
  • Reactive API Calls with HttpClient
  • Form Submission Handling
  • Spring Boot REST API Integration
  • MySQL Database Interaction using JPA

Conclusion

With this tutorial, you now have a complete understanding of how to build a full stack form-handling application using Angular for the frontend and Spring Boot for the backend. Whether you’re a beginner or preparing for a real-world project, this setup covers everything from frontend form design to backend API integration and database interaction.

Youtube Video –

Explore our more articles

Leave a Comment