Angular Form Handling with Spring Boot

In this tutorial, we will create a simple form-handling application using Spring Boot for the backend and Angular for the front end. We will demonstrate how to submit a form from Angular to Spring Boot and handle the form data on the backend.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed
  • Apache Maven installed
  • Node.js and npm installed
  • Angular CLI installed (npm install -g @angular/cli)
  • An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed

Step 1: Setting Up the Spring Boot Backend

1.1 Create a Spring Boot Project

  1. Open Spring Initializr:

  2. Configure Project Metadata:

    • Project: Maven Project
    • Language: Java
    • Spring Boot: Select the latest version of Spring Boot
    • Group: com.example
    • Artifact: form-handling
    • Name: form-handling
    • Description: Form Handling Service
    • Package Name: com.example.formhandling
    • Packaging: Jar
    • Java Version: 17 (or your preferred version)
    • Click Next.
  3. Select Dependencies:

    • On the Dependencies screen, select:
      • Spring Web
    • Click Next.
  4. Generate the Project:

    • Click Generate to download the project zip file.
    • Extract the zip file to your desired location.
  5. Open the Project in Your IDE:

    • Open your IDE and import the project as a Maven project.

1.2 Update application.properties

Open the application.properties file located in the src/main/resources directory and add the following configuration:

server.port=8080

Explanation:

  • Configures the server port to 8080.

1.3 Create a Form Model

Create a User model class in the com.example.formhandling.model package:

package com.example.formhandling.model;

public class User {

    private String name;
    private String email;

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Explanation:

  • A simple User class with name and email fields, along with their getters and setters.

1.4 Create a Controller

Create a FormController class in the com.example.formhandling.controller package:

package com.example.formhandling.controller;

import com.example.formhandling.model.User;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RestController;

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

    @PostMapping("/submit")
    public String submitForm(@RequestBody User user) {
        return "Form submitted successfully! Name: " + user.getName() + ", Email: " + user.getEmail();
    }
}

Explanation:

  • @CrossOrigin(origins = "http://localhost:4200"): Enables CORS for requests from the Angular frontend running on localhost:4200.
  • @RestController: Marks the class as a REST controller.
  • @RequestMapping("/api"): Maps requests to /api.
  • submitForm(@RequestBody User user): Handles POST requests to /api/submit and returns a success message.

1.5 Run the Spring Boot Application

Run the application by executing the FormHandlingApplication class. The backend should be up and running on http://localhost:8080.

Step 2: Setting Up the Angular Frontend

2.1 Create an Angular Project

  1. Open a terminal and run the following command to create a new Angular project:
ng new form-handling-client
  1. Navigate to the project directory:
cd form-handling-client

2.2 Install Dependencies

Install Bootstrap for styling:

npm install bootstrap

Add Bootstrap to angular.json:

"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.min.css"
],

2.3 Create a Service

Generate the FormService:

ng generate service services/form

Edit form.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

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

  private baseUrl = 'http://localhost:8080/api/submit';

  constructor(private http: HttpClient) { }

  submitForm(user: any): Observable<any> {
    return this.http.post(this.baseUrl, user, { responseType: 'text' });
  }
}

Explanation:

  • @Injectable({ providedIn: 'root' }): Marks the service as injectable and available throughout the app.
  • HttpClient: Service for making HTTP requests.
  • submitForm(user: any): Sends a POST request to submit the form data.

2.4 Create a Form Component

Generate the FormComponent:

ng generate component components/form

Edit form.component.ts:

import { Component } from '@angular/core';
import { FormService } from '../../services/form.service';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent {
  user = { name: '', email: '' };
  message = '';

  constructor(private formService: FormService) { }

  submitForm() {
    this.formService.submitForm(this.user).subscribe(response => {
      this.message = response;
    }, error => {
      console.error('Form submission error: ', error);
      this.message = 'Could not submit the form';
    });
  }
}

Edit form.component.html:

<div class="container mt-5">
  <div class="row justify-content-center">
    <div class="col-md-6">
      <div class="card">
        <div class="card-header">Submit Form</div>
        <div class="card-body">
          <form (ngSubmit)="submitForm()">
            <div class="form-group">
              <label for="name">Name</label>
              <input type="text" id="name" class="form-control" [(ngModel)]="user.name" name="name" required>
            </div>
            <div class="form-group">
              <label for="email">Email</label>
              <input type="email" id="email" class="form-control" [(ngModel)]="user.email" name="email" required>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
          </form>
          <div class="mt-3" *ngIf="message">{{ message }}</div>
        </div>
      </div>
    </div>
  </div>
</div>

Explanation:

  • FormComponent binds the form data to the user object and sends it to the backend upon submission.
  • Displays a success or error message based on the response from the backend.

2.5 Update Angular Routing

Edit app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormComponent } from './components/form/form.component';

const routes: Routes = [
  { path: 'form', component: FormComponent },
  { path: '', redirectTo: '/form', pathMatch: 'full' }
];

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

Explanation:

  • Defines a route for the FormComponent.
  • Redirects the root path to /form.

2.6 Update Angular App Module

Edit app.module.ts:

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormComponent } from './components/form/form.component';

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

Explanation:

  • Imports necessary modules for the Angular app.
  • Declares the components used in the app.
  • Sets up the app's root module.

2.7 Run the Angular Application

Open a terminal in the Angular project directory and run the application:

ng serve

Visit http://localhost:4200 in your web browser to see the application.

Conclusion

In this tutorial, we created a simple form handling application using Spring Boot for the backend and Angular for the frontend. We demonstrated how to submit a form from Angular to Spring Boot and handle the form data on the backend. By following this structure, you can extend and customize the application as needed.

Comments