Angular响应式表单:如何仅对对象的tip字段应用验证器
问题描述
我有一个包含FormArray的Angular响应式表单,初始化时会向表单数组中推入带默认值的表单控件,代码如下:
formValues?.tipsAndTricks?.forEach((tipAndTrick) => { this.tipsAndTricks.push( this.fb.control( { id: tipAndTrick.id, tip: tipAndTrick.tip }, { validators: [Validators.required, Validators.minLength(25), Validators.maxLength(2000)], updateOn: 'change' } ) ) })
现在验证器无法正常工作,因为验证器被应用在了整个{ id: tipAndTrick.id, tip: tipAndTrick.tip }对象上,请问如何将这些验证器仅应用于对象的tip字段?
解决方案
你需要把FormArray中的每一项从FormControl改成FormGroup,这样就能给tip字段对应的单独控件添加验证器,id字段可作为无需验证的控件存在。修改后的代码如下:
formValues?.tipsAndTricks?.forEach((tipAndTrick) => { this.tipsAndTricks.push( this.fb.group({ id: this.fb.control(tipAndTrick.id), tip: this.fb.control( tipAndTrick.tip, { validators: [Validators.required, Validators.minLength(25), Validators.maxLength(2000)], updateOn: 'change' } ) }) ) })
说明
- 原写法将整个对象作为单个FormControl的值,验证器会对整个对象做校验,无法正确识别
tip字段的内容,导致验证失效。 - 改用FormGroup后,每个字段对应独立的FormControl,验证器仅作用于
tip控件,能正常触发必填、长度范围的校验逻辑。
内容的提问来源于stack exchange,提问作者PepeW
相关产品推荐
相关产品推荐

