I have a form group which is composed by a single form array:
ngOnInit() {
this.deviceDetailsFormGroup = this._formBuilder.group({
deviceDetails: this._formBuilder.array([
this.buildDeviceDetailsForm()
])
});
}
Each control in the Form Array has required validators:
buildDeviceDetailsForm(): FormGroup {
return this._formBuilder.group({
ipAddressCtrl: [
"",
[Validators.pattern(ipaddressPattern), Validators.required]
],
hostnameCtrl: [
"",
[
Validators.required,
Validators.maxLength(30),
Validators.minLength(5)
]
]
});
}
Below are my push and remove functions to the Form Array:
addNewDevice() {
this.deviceItems = this.deviceDetailsFormGroup.get(
"deviceDetails"
) as FormArray;
if (this.deviceItems.length > MAX_DEVICES) {
this.toastNotif.errorToastNotif(
`A maximum of ${MAX_DEVICES} devices can be selected for a single job scan`,
"Too many devices selected"
);
return;
}
if (this.deviceDetailsFormGroup.invalid) {
return;
}
let mapIP = new Map<string, number>();
// Warn about duplicate IP's in form
this.deviceItems.controls.forEach(ctrl => {
if (mapIP[ctrl.value.ipAddressCtrl] === 0) {
this.toastNotif.warningToastNotif(
"You have entered duplicate IP's in the form fields",
"Duplicate" + " IP's"
);
}
mapIP[ctrl.value.ipAddressCtrl] = 0;
});
this.deviceItems.push(this.buildDeviceDetailsForm());
}
removeDevice(i: number) {
this.deviceItems.removeAt(this.deviceItems.length - 1);
}
When I push new elements to the Form Array, they're marked as invalid although they're untouched and pristine. I understand that's caused by the Validators and empty default values set when I create the new FormGroup.
Is it possible to avoid this behavior so the FormArray elements are marked as errors only if they're touched ?
Thanks in advance.