Angular反应性表单-排除表单提交中的空白字段

时间:2018-11-06 19:37:10

标签: javascript angular typescript

我试图仅从表单中获取具有用户输入值的字段。从中得到的JSON对象仍然包含用于空输入的空引号(请参见下文)。有没有一种方法可以在提交表单时排除空白字段?谢谢!

当前:     6 digits

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

1 个答案:

答案 0 :(得分:1)

如果您没有为表单控件分配空值,那么这些将自动为null

考虑到这是创建表单的方式:

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);
  }

}

对于未填写的字段,表单值将产生null。然后,您可以像这样从value删除它们:

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);
}

这是您推荐的Sample StackBlitz