【发布时间】:2018-11-21 17:46:47
【问题描述】:
我正在使用带有反应形式的 Angular 6。其中一个表单字段是 FormArray,它在用户单击“添加”按钮时添加控件。
在FormArray中,我想检查FormControl值是否已经存在于FormArray中。
这可以正常工作,直到用户单击“添加”按钮重置先前的控件错误并将控件标记为有效,尽管它仍然具有重复值。
这是在表单数组中添加控件的函数:
onAddIPAddress() {
if (( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).length < 8) {
const control = new FormControl(null, Validators.compose([
Validators.required,
Validators.pattern(this.ipaddressPattern),
this.forbiddenIPs.bind(this),
this.onDuplicateIPFormArray.bind(this)
]));
( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).push(control);
} else {
return;
}
}
然后,这是自定义验证器代码:
onDuplicateIPFormArray(control: FormControl): {
[s: string]: boolean
} {
if (
( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).length > 1 &&
!( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value.includes(null) &&
( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value.indexOf(control.value) !== -1)
{
console.log(( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value.indexOf(control.value));
return {
duplicateIP: true
};
}
return null;
}
从控制台,我可以看到 IndexOf 值不正确,但无法理解原因。
有什么办法可以解决这个问题吗?
谢谢
【问题讨论】:
-
据我了解,您将新创建的 FormControl 的值设置为 null ,然后将 null 用于 indexOf
-
我将初始 FormControl 值设置为 null,然后在验证器中执行以下操作: - 检查 FormArray 长度是否 > 1, - 检查 FormArray 控件之一是否不为空,如果没有则为空使用获取FormControl的indexOf值
标签: angular angular-reactive-forms