angular - 使用 setValidators 验证动态字段
问题描述
我正在使用动态表单控件通过使用https://www.c-sharpcorner.com/blogs/creating-form-controls-dynamically-in-angular-7-project的参考来创建动态字段
我想使用验证动态字段在 Angular 6 中setValidators
。updateValueAndValidity
以下是我使用过的语法,但它不起作用。
(<FormArray>this.addQuestionForm.get('other')).setValidators([Validators.required]);
(<FormArray>this.addQuestionForm.get('other')).updateValueAndValidity();
还让我知道如何参考“ <FormArray>this.addQuestionForm.get('other')
”删除动态添加的字段
谢谢
解决方案
您必须对 (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);
推荐阅读
- python - 为什么最后一个向量被复制到python中列表的所有元素
- spring - @RequestParam 上的约束验证似乎不起作用
- python - pandas to_numeric(..., downcast='float') 失去精度
- r - 如何根据 r 中的日期/日期拆分和制作新的 csv 文件?
- java - Java:为什么我的 toString 方法打印错误信息?
- java - 如何通过二维数组错误调用方法
- php - 防止从外部网站重定向到我的域
- javascript - 意外令牌或使用 JSON 解析转换循环结构
- events - Gitlab push events
- jpa - 如何在 JPA 中使用多个外键?