[英]How to iterate over FormArray in FormGroup in an Angular reactive Form
The Structure of my form is as shown below 我的表格的结构如下所示
-MainForm(ParentForm)
-FormGroup(MedicineGroup)
-FormArray(MedicineArray)
I wanted to iterate MedicineArray
for which, i did some research and wrote the below code 我想迭代MedicineArray
为此,我做了一些研究并编写了以下代码
for (let control of soForm.get('MedicineGroup').controls['MedicineArray'].controls) {
medObj.name.push(control.controls['MedName'].value);
}
The code is working fine but i am getting a warning, which says 该代码工作正常,但我收到警告,说
Property 'controls' does not exist on type 'AbstractControl'.
Is there any other or better way to iterate a FormArray which is inside a FormGroup? 还有其他更好的方法可以迭代FormGroup内部的FormArray吗?
You can try using ['controls']
instead of .controls
: 您可以尝试使用['controls']
而不是.controls
:
for (let control of soForm.get('MedicineGroup')['controls']['MedicineArray']['controls']) {
// ...
}
Another option would be: 另一种选择是:
const formArray = soForm.get('MedicineGroup.MedicineArray') as FormArray;
console.log(formArray);
It's a good practice to access nested controls using dot notation. 使用点表示法访问嵌套控件是一个好习惯。
The reason this is occurring is because the type system understands that you have an AbstractControl, because AbstractControl.prototype.get()
returns an AbstractControl
, but it doesn't know which concrete AbstractControl you are referencing, so accessing a controls
property causes this warning. 发生这种情况的原因是因为类型系统理解您具有AbstractControl,因为AbstractControl.prototype.get()
返回了AbstractControl
,但是它不知道您要引用哪个具体的AbstractControl,因此访问controls
属性会导致此警告。 。
You have some options as to how to solve it, casting or introducing another symbol, but the method is the same: provide better type information: 您可以选择如何解决,强制转换或引入另一个符号的方法,但是方法是相同的:提供更好的类型信息:
let aFormArray: FormArray = soForm.get('MedicineGroup.MedicineArray');
for (let c of aFormArray.controls) {
medObj.name.push(c.controls['MedName'].value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.