How to Use Angular 13 HttpClient API to Post FormData

Last updated on: by Digamber
Angular 13 FormData tutorial; In this detailed post, we will discover how to use Angular 13 HttpClient API to Post FormData to a web server.

Forms are an essential part of any web or mobile applications, and Forms allow us to gather data from the users and send that data to the webserver.

HTTP requests are used to perform CRUD operations; similarly, the HttpClient API in Angular lets you perform the HTTP calls. Moreover, this service is an injectable class that helps you handle HTTP requests.

Each request conjugates multiple signatures, and the return type varies based on the signature that is called the response.

To send the form data in Angular, we are going to learn specifically about the FormData object but also how to use it in an Angular application.

It’s a JavaScript object, which allows us to develop a set of key/value data structure representing form fields and their respective values.

In this step by step article, we will take the help of Angular HttpClient API to send FormData to a web server by using the Http POST method.

Angular 13 Post FormData with HttpClient API Example

  • FormData Methods
  • Setting up Node & Express Server
  • Set up Angular App
  • Build Form with Reactive Forms and Bootstrap 4
  • POST FormData with Angular HttpClient API

FormData Methods

You can initialize FormData object by creating an instance from new FormData interface as given below.

const formData = new FormData()

FormData Methods

Once the FormData instance is created then there are various methods available through FormData, which allows you to manage the data as per your requirement.

MethodsDescription
FormData.append()It includes a new value on a pre-existing key within a FormData object. If the key already exists, then the value will be added to that key without removing the first key.
FormData.delete()It deletes a key and value pair from the FormData object.
FormData.entries()FormData returns an iterator which allows looping over a set of key-value pair presenting in the object.
FormData.get()It returns the value associated with a given set of a key from the FormData object. However, if more values appended, then it will return the first value.
FormData.getAll()Returns all the values associated with a key from the FormData object.
FormData.has()It returns true if the key exists in FormData object.
FormData.keys()Returns an iterator which allows looping over all the keys of the key-value data structure in this object.
FormData.set()It is used to set the value into the FormData object with the particular key. Value is replaced if a key already exists in the FormData object.
FormData.values()Returns an iterator which allows looping over all the values existing in this object

You can check out more about the FormData object here.

Setting up Node & Express Server

For the demo purpose, we are using the existing REST API built with Node, Express, MongoDB, and Multer NPM modules. By using this existing node server you can easily store the user data such as name and avatar (profile image) to the mongoDB database.

Git clone the angular node file upload project on your system, you can use the given command.

git clone https://github.com/SinghDigamber/angular-node-fileupload-formdata.git

After that, navigate to the backend folder and run following command.

cd backend

Next, run the given below command to start the mongoDB database.

mongod

Next, run the nodemon server:

nodemon

Once your server is up and running, then you can check your Node server app on the following Urls: http://localhost:4000

  • /api: Users List
  • /api/create-user: Create User

Set up Angular App

Run following command to install the basic Angular app:

ng new angular-formdata

In order to remove strict type warnings or error make sure to set “strict”: false under compilerOptions property in tsconfig.json file.

Run the command to install the Bootstrap 4.

npm install bootstrap

Go to angular.json file and inject the bootstrap style sheet inside the styles array like given below.

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

Now, your Angular app is ready to be started via following command.

ng serve --open

Now, create a component where we will put all of our form data logic in an Angular app.

ng g c file-upload

Build Form with Reactive Forms and Bootstrap 4

In this step we will create a Form for user, by using this form user can submit data and send it on the web server.

We will be using Angular’s Reactive Forms approach to get and set the data, first import the ReactiveFormsModule in the app.module.ts file.

import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
  declarations: [...],
  imports: [
    ReactiveFormsModule
  ],
  bootstrap: [...]
})
export class AppModule { }

Then create a form with the help of Bootstrap 4 and Reactive Forms APIs such as FormBuilder and FormGroup.

Go to app/file-upload.component.html file and add the following code:

<div class="container">
    <form [formGroup]="form" (ngSubmit)="submitForm()">
        <div class="form-group">
            <input type="file" (change)="uploadFile($event)">
        </div>
        <div class="form-group input-group-lg">
            <input class="form-control" placeholder="Name" formControlName="name">
        </div>
        <div class="form-group">
            <button class="btn btn-danger btn-block btn-lg">Create</button>
        </div>
    </form>
</div>

Next, go to file-upload.component.ts file and add the following code inside of it. Here, we are setting up the user entered data in the Reactive Forms form: FormGroup object (name, avatar).

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss'],
})
export class FileUploadComponent implements OnInit {
  form: FormGroup;
  constructor(public fb: FormBuilder, private http: HttpClient) {
    this.form = this.fb.group({
      name: [''],
      avatar: [null],
    });
  }
  ngOnInit() {}
  uploadFile(event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.form.patchValue({
      avatar: file,
    });
    this.form.get('avatar').updateValueAndValidity();
  }
  submitForm() {
    var formData: any = new FormData();
    formData.append('name', this.form.get('name').value);
    formData.append('avatar', this.form.get('avatar').value);
    this.http
      .post('http://localhost:4000/api/create-user', formData)
      .subscribe({
        next: (response) => console.log(response),
        error: (error) => console.log(error),
      });
  }
}

Angular FormData

POST FormData with Angular HttpClient API

To make the HTTP POST request in Angular, first import the HttpClientModule API in app.module.ts file.

import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [...],
  imports: [
     HttpClientModule
  ],
  bootstrap: [...]
})
export class AppModule { }

In the next step, import HttpClient in file-upload.component.ts file, then inject it into the constructor. The Angular HTTP API will allow you to make GET, POST, DELETE or UPDATE request in your Angular app.

import { HttpClient } from '@angular/common/http';
constructor(
    private http: HttpClient
) {...}

Create formData instance from FormData object and use the append() method to set the values. Define the name and avatar value in the append method from the Reactive Forms form (FormGroup) object.

submitForm() {
  var formData: any = new FormData();
  formData.append("name", this.form.get('name').value);
  formData.append("avatar", this.form.get('avatar').value);
  this.http.post('http://localhost:4000/api/create-user', formData).subscribe(
    (response) => console.log(response),
    (error) => console.log(error)
  )
}

Next, make the HTTP POST request in Angular. Pass the /create-user API in the first argument and pass the formData in the second argument.

Angular Post FormData

Final file-upload.component.ts file:

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

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss']
})
export class FileUploadComponent implements OnInit {
  form: FormGroup;
  constructor(
    public fb: FormBuilder,
    private http: HttpClient
  ) {
    this.form = this.fb.group({
      name: [''],
      avatar: [null]
    })
  }
  ngOnInit() { }
  uploadFile(event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.form.patchValue({
      avatar: file
    });
    this.form.get('avatar').updateValueAndValidity()
  }
  submitForm() {
    var formData: any = new FormData();
    formData.append("name", this.form.get('name').value);
    formData.append("avatar", this.form.get('avatar').value);
    this.http.post('http://localhost:4000/api/create-user', formData).subscribe(
      (response) => console.log(response),
      (error) => console.log(error)
    )
  }
}

In the last step, we will open app.component.html file and add the component tag.

<app-file-upload></app-file-upload>

Conclusion

Finally, we have learned how to use Angular HttpClient API to Post FormData (multipart/form-data). I hope this tutorial helped you a lot, please consider it sharing with others.

Git Repo

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.