我有一个由单个表单数组组成的表单组:
ngOnInit() {
this.deviceDetailsFormGroup = this._formBuilder.group({
deviceDetails: this._formBuilder.array([
this.buildDeviceDetailsForm()
])
});
}
表单数组中的每个控件都需要验证器:
buildDeviceDetailsForm(): FormGroup {
return this._formBuilder.group({
ipAddressCtrl: [
"",
[Validators.pattern(ipaddressPattern), Validators.required]
],
hostnameCtrl: [
"",
[
Validators.required,
Validators.maxLength(30),
Validators.minLength(5)
]
]
});
}
以下是我对表单数组的推送和删除函数:
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);
}
当我将新元素推送到表单数组时,它们被标记为无效,尽管它们未受影响且原始。我知道这是由验证器和创建新的时设置的空默认值引起的FormGroup
.
是否可以避免这种行为FormArray
仅当元素被触摸时才会被标记为错误?
提前致谢。
我有一个非常相似的情况,每当我添加一个新的formGroup
to my formArray
即使它们是,它的验证也会被触发untouched
& pristine
。原来如果用按钮动态添加formGroups
它将默认操作为提交事件,如果您不指定按钮类型,则会触发验证运行。
Adding type="button"
解决了问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)