首页 > 解决方案 > 使用 setValidators 验证动态字段

问题描述

我正在使用动态表单控件通过使用https://www.c-sharpcorner.com/blogs/creating-form-controls-dynamically-in-angular-7-project的参考来创建动态字段 我想使用验证动态字段在 Angular 6 中setValidatorsupdateValueAndValidity

以下是我使用过的语法,但它不起作用。

(<FormArray>this.addQuestionForm.get('other')).setValidators([Validators.required]);
(<FormArray>this.addQuestionForm.get('other')).updateValueAndValidity();

还让我知道如何参考“ <FormArray>this.addQuestionForm.get('other')”删除动态添加的字段

谢谢

标签: angularvalidation

解决方案


您必须对 (this.addQuestionForm.get('other')) 的每个控件进行循环并在每个组件上应用验证

(<FormArray>this.addQuestionForm.get('other')).controls.forEach((control) => {
    control.setValidators([Validators.required]);
    control.updateValueAndValidity();
});

如果要删除 formArray 中动态添加的字段,则必须获取要删除的元素的索引

由于 FormArray 类具有 removeAt ,它采用索引。如果你不知道索引,你可以做一个解决方法:

this.addQuestionForm.get('other').removeAt(index);

推荐阅读