Working with FormData in Angular 18

Working with FormData in Angular 18

In this comprehensive tutorial, we'll delve into the details of handling FormData in Angular 18 and TypeScript, equipping you with the skills to seamlessly integrate form data submission into your web applications. Specifically, you'll learn about crafting and dispatching POST requests containing FormData payloads using Angular 18 HttpClient.

Forms play a pivotal role in web development, serving as the conduit through which users provide crucial data that needs to be transmitted to a server. Whether it's user registrations, file uploads, or content submissions, understanding how to effectively manage form data is essential for building robust and interactive web applications.

Throughout this tutorial, we'll learn how to work with forms in Angular 18, focusing particularly on the use of FormData. You'll grasp how to harness the power of Angular's HttpClient module to seamlessly transmit form data to backend servers via HTTP POST requests.

Before delving into the details of FormData manipulation and HTTP requests in Angular 18, it's imperative to ensure that your development environment is properly configured. If you're new to the Angular ecosystem or need a refresher, fear not! We'll guide you through the process of setting up an Angular 18 project step by step, ensuring that you're well-equipped to embark on this exhilarating journey.

To get started, make sure to check out our comprehensive guide on installing and configuring an Angular 18 project, where you'll find detailed instructions on the prerequisites and setup procedures. Whether you're a seasoned Angular developer or a newcomer to the framework, this guide will lay the foundation for your foray into the fascinating realm of Angular development.

Angular FormData

Why using FormData

Forms can be used in a variety of ways in JavaScript and HTML. Different frameworks (such as Angular) have also added new ways to handle forms.

In this tutorial, we'll look at 'FormData,' a browser API for handling form data, as the name implies. This API provides methods and properties that allow you to easily access and work with form elements and their values.

It's especially useful when working with client-side frameworks like Angular because it lets you conveniently arrange form data to be sent with POST HTTP requests.

Consider FormData as a JavaScript representation of a form rather than an HTML form. Additionally, you can create a FormData instance directly from an HTML form.

When you use the FormData API, you can create a compilation of key/value elements that correspond to the contents of form fields and their values. Angular 18 HttpClient can then be used to send this data to the server.

It's also worth noting that a FormData instance is equivalent to an HTML form sent using the multipart/form-data encoding.

How to use FormData in angular 18

Let's look at how to create a FormData instance and send it with a HttpClient POST request in Angular 18.

We'll suppose you have a server running at http://localhost:3000 with a /upload endpoint that accepts POST requests for file uploads.

Check out Nest.js Tutorial: File Uploading with Multer and Serving Static Files in Nest if you want to make a server for uploading files.

Create an angular 18 component for upload

If you've already created an Angular 18 project with Angular CLI, navigate to the root folder of your project and run the following command to generate the component we'll be working with:

$ ng generate component upload

Adding a form

Open the src/app/upload/upload.component.html file and add the following form:

<h1>Angular 18 FormData (multipart/data-form) Example</h1>
<div>
    <form [formGroup] = "uploadForm" (ngSubmit)="onSubmit()">      
      <div>
        <input type="file" name="profile" (change)="onFileSelect($event)" />
      </div>
      <div>
        <button type="submit">Upload</button>
      </div>
    </form>
  </div>
</div>

You can also check this example with HTML textarea.

Importing angular forms module and APIs

Next, open the src/app/upload/upload.component.ts file and start by importing these APIs:

import { FormBuilder, FormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

We import FormBuilder and FormGroup from the @angular/forms package which are necessary to create a reactive form in Angular 18. We also import HttpClient that will be used to send data to the server.

Also, make sure to import ReactiveFormsModule and HttpClientModule in your main module application which can be found in the src/app/app.module.ts file and add them to the imports array.

The use of HttpClient calls directly from your components violates the separation of concerns principle, but this is just a simple example. Typically, you would need to create a service and then make a HttpClient call from it.

Create an angular 18 reactive form

Next define the SERVER_URL and uploadForm variables in your component:

export class UploadComponent implements OnInit {

  SERVER_URL = "http://localhost:3000/upload";
  uploadForm: FormGroup;  

Next, import and inject HttpClient and FormBuilder:

export class UploadComponent implements OnInit {
  constructor(private formBuilder: FormBuilder, private httpClient: HttpClient) { }

Next, create a reactive form in ngOnInit() method of the component which gets called when the component is initialized:

  ngOnInit() {
    this.uploadForm = this.formBuilder.group({
      profile: ['']
    });
  }

Next, let's add the onFileSelect() method which gets called when a file is selected by the user:

  onFileSelect(event) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.uploadForm.get('profile').setValue(file);
    }
  }

We simply check if at least one file is selected and we set the profile field of uploadForm to the selected file.

Sending the form data with Angular 18 HttpClient

Finally, let's see how we can use FormData to send multipart/form-data to our server. Let's define the onSubmit() method:

  onSubmit() {
    const formData = new FormData();
    formData.append('file', this.uploadForm.get('profile').value);

    this.httpClient.post<any>(this.SERVER_URL, formData).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
  }

We simply create an instance of FormData, next we add fields with their values using the append() method of FormData. In our example, we only add a field named file which holds the value the selected file. Finally we use the post() method of HttpClient to send the form data to the server.

For reference, FormData provides the following methods for working with form data:

  • The FormData.append() appends a new value for an existing key, or adds the key if it does not exist.
  • The FormData.delete() method deletes a key/value pair from a FormData object.
  • The FormData.entries()method provides an iterator for going through all key/value pairs of the instance.
  • The FormData.get() method Returns the first value associated with a given key from within a FormData object.
  • The FormData.getAll() method provides an array of all the values associated with a specific key.
  • The FormData.has() methods provides a boolean indicating whether a FormData instance contains a specific key.
  • The FormData.keys() method provides an iterator for going through all the keys contained in the form instance.
  • The FormData.set()method sets a new value for an existing key inside a FormData object, or adds the key/value if it does not exist.
  • The FormData.values() method provides an iterator for going through all values contained in this object.

Conclusion

In this tutorial, we've seen how to send post multi-part form data to a server using TypeScript, Angular 18, HttpClient and FormData.

When it comes to JavaScript and HTML, forms can be used in a number of ways. A variety of frameworks (such as Angular 18) have also introduced new methods for working with forms.

In this tutorial, we took a look at FormData which is a browser API that, as the name implies, is used to work with form data. This API provides methods and properties that allow you to easily access and work with form elements and their values from JavaScript or TypeScript in our case.

If you're working with Angular 18, it's especially useful because it allows you to easily assemble form data to be sent with POST HTTP requests, which is particularly convenient.


  • Date: