简体   繁体   English

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

[英]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). 从中得到的JSON对象仍然包含用于空输入的空引号(请参见下文)。 Is there a way to exclude empty fields upon form submit? 有没有一种方法可以在提交表单时排除空白字段? Thank you! 谢谢!

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

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

If you don't assign an empty value to the form controls, then these will automatically be null . 如果您没有为表单控件分配空值,那么这些控件将自动为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. 对于未填写的字段,表单值将产生null You can then remove them from the value like this: 然后可以将它们从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);
}

Here's a Sample StackBlitz for your ref. 这是供您参考的示例StackBlitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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