Yeol
Yeol

Reputation: 139

Angular Reactive Forms - Exclude empty fields on form submit

I am trying to get only fields from the form with values entered by the user. The resulting JSON object from still contains empty quotation marks for empty inputs (see below). Is there a way to exclude empty fields upon form submit? Thank you!

Current: { "user": "", "directory": "documents", "filename": [ "a", "", "" ] }

Goal: { "directory": "documents", "filename": [ "a" ] }

Upvotes: 2

Views: 6412

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

If you don't assign an empty value to the form controls, then these will automatically be null.

Considering this is how you're creating your form:

import { Component } from '@angular/core';
import { FormBuilder, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private fb: FormBuilder) {}

  userForm = this.fb.group({
    user: [],
    directory: [],
    filename: this.fb.array([])
  });

  addFile() {
    (<FormArray>this.userForm.get('filename')).push(this.fb.control(null));
  }

  get files() {
    return (<FormArray>this.userForm.get('filename')).controls;
  }

  onSubmit() {
    console.log(this.userForm.value);
  }

}

The form value would yield null for fields that were not filled. You can then remove them from the value like this:

onSubmit() {
  let formValue = { ...this.userForm.value };

  for (let prop in formValue) {
    if (!formValue[prop]) {
      delete formValue[prop];
    }

    if (Array.isArray(formValue[prop])) {
      let resultArray = formValue[prop].filter(item => item);
      if (resultArray.length > 0) {
        formValue[prop] = resultArray;
      } else {
        delete formValue[prop];
      }
    }
  }
  console.log(formValue);
}

Here's a Sample StackBlitz for your ref.

Upvotes: 3

Related Questions