我正在处理一项要求,我必须遍历component.ts文件中定义的“ formArray”控件,以设置对表单提交的验证。我收到类似“ .forEach不是函数”的错误,Mycode如下:
component.ts
ip_addresses_arr: any;
this.companyForm = this.fb.group({
company_ip_addresses: this.fb.array([this.fb.group({
id: 0,
start_ip: new FormControl('', Validators.pattern("^([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})$")),
end_ip: new FormControl('', Validators.pattern("^([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})$"))
})]),
});
我在formArray上的forEachloop是:
saveCompanyInfo() {
this.ip_addresses_arr = this.companyForm.get('company_ip_addresses');
this.ip_addresses_arr.forEach(eachfield => {
console.log("each field",this.ip_addresses_arr);
if(eachfield.start_ip != "" && eachfield.end_ip == ""){
console.log("coming inside end_ip is empty");
eachfield.end_ip.setErrors({'incorrect': true});
eachfield.end_ip.markAsTouched();
}else if(eachfield.end_ip != "" && eachfield.start_ip == ""){
console.log("coming inside start_ip is empty");
eachfield.start_ip.setErrors({'incorrect': true});
eachfield.start_ip.markAsTouched();
}else{
eachfield.start_ip.setErrors(null);
eachfield.end_ip.setErrors(null);
}
});
if (this.companyForm.valid) {
-----------------
-----------------
}
}
我的问题是说 .forEach不是函数。谁能解释一下代码中的错误。任何帮助,将不胜感激。谢谢。
答案 0 :(得分:0)
这实际上是一个小问题,打字稿,编辑者抱怨这是因为formInstance.get('controlName')
返回了Abstract控件。您必须告诉他们您收到的控件是一个FormArray,您可以这样做:
this.ip_addresses_arr = this.companyForm.get('company_ip_addresses') as FormArray;
您需要像这样遍历控件。
this.ip_addresses_arr.controls.forEach()
您没有正确访问控件
saveCompanyInfo() {
this.ip_addresses_arr = this.companyForm.get('company_ip_addresses') as FormArray;
this.ip_addresses_arr.controls.forEach(eachfield => {
if(eachfield.get('start_ip').value != "" && eachfield.get('end_ip').value == ""){
console.log("coming inside end_ip is empty");
eachfield.get('end_ip').setErrors({'incorrect': true});
eachfield.get('end_ip').markAsTouched();
}else if(eachfield.get('end_ip').value != "" && eachfield.get('start_ip').value == ""){
console.log("coming inside start_ip is empty");
eachfield.get('start_ip').setErrors({'incorrect': true});
eachfield.get('start_ip').markAsTouched();
}else{
eachfield.get('start_ip').setErrors(null);
eachfield.get('end_ip').setErrors(null);
}
});
}