You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FormArray已存在错误,为何hasError方法仍返回false?

问题原因与解决方案:FormArray调用hasError返回false但error对象存在

嘿,这个问题我之前也碰到过!核心原因是Angular里FormArray的hasError()方法默认行为和FormControl不一样。

你看,你是直接给emails这个FormArray实例设置了incorrectEmail错误:

this.emailForm.controls['emails'].setErrors({'incorrectEmail': true});

这个错误确实会出现在FormArray的errors对象里,但当你调用hasError('incorrectEmail')时,Angular默认会去遍历这个FormArray里的所有子FormControl,检查它们有没有这个错误,而不是检查FormArray自己的错误。

要解决这个问题,你只需要在调用hasError的时候加上第二个参数{onlySelf: true},明确告诉Angular只检查当前FormArray自身的错误:

// 修改前:返回false
console.log(this.emailForm.get('emails').hasError('incorrectEmail'));
// 修改后:返回true
console.log(this.emailForm.get('emails').hasError('incorrectEmail', {onlySelf: true}));

另外补充一点:如果你是想给整个FormArray添加自定义验证错误,这种直接给FormArray设置错误的方式是没问题的,就是要记得用onlySelf参数来校验自身错误。如果你的业务是要标记整个表单组的错误,也可以考虑把错误设置到父FormGroup上,不过这得看你的具体需求啦。

内容的提问来源于stack exchange,提问作者Lars Hendriks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:07:37