In the scenario where form controls are not given an empty value, they will automatically default to null
.
If you are constructing your form in the following manner:
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);
}
}
Any unfilled fields in the form would be interpreted as null
. To exclude these from the value
, consider the following approach:
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);
}
For reference, here is a Sample StackBlitz of this implementation.