简体   繁体   中英

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" ] }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM