[英]Casting a FormArray to an array angular
I have a FormArray of FormGroups, i want to iterate over the FormArray and detect which FormGroups are valid.我有一个 FormGroups 的 FormArray,我想遍历 FormArray 并检测哪些 FormGroups 是有效的。 However i am unable to do so as i am unable to iterate over a FormArray as it is not of type Array or string.但是我无法这样做,因为我无法遍历 FormArray,因为它不是 Array 或 string 类型。 My logic was to somehow cast the FormArray into an Array if possible.如果可能,我的逻辑是以某种方式将 FormArray 转换为 Array。 However i do not know the syntax in typescript for this.但是我不知道打字稿中的语法。
this.applicationFormArray = new FormArray([ this.selectAppFormGroup = new FormGroup({ }), this.generalAppFormGroup = new FormGroup({ }), this.fileModeFormGroup = new FormGroup({ }), this.accessListFormGroup = new FormGroup({ }), ]);
checkValidity() { var foo = this.applicationFormArray as Array<>; for(var element of this.applicationFormArray){ if(element.valid) { //do something } }
You can use map
together with the length
of FromArray
and the at
method: 您可以将map
与FromArray
的length
和at
方法一起使用:
let array = new Array(this.applicationFormArray.length)
.map((v, index) => this.applicationFormArray.at(index) as FormGroup);
Although the for version is not too bad either: 尽管for版本也不错:
for (let i =0;i< this.applicationFormArray.length;i++) {
const element = this.applicationFormArray.at(i);
if (element.valid) {
//do something
}
}
一种可能的解决方案是使用过滤器并仅获取有效表格。
const myValidForms = formArray.controls.filter(myForm => myForm.valid);
You can convert a FormArray to a regular Array with the FormArray's value property.您可以使用 FormArray 的 value 属性将 FormArray 转换为常规 Array。 This is what worked for me.这对我有用。 Using the value property on a FormGroup returns an object literal and on a FormArray it returns an array.在 FormGroup 上使用 value 属性返回一个对象文字,在 FormArray 上它返回一个数组。
let newArr = this.applicationFormArray.value
newArr.map(...)
In your example it would look like this:在您的示例中,它看起来像这样:
var foo = this.applicationFormArray.value;
for(var element of foo){
if(element.valid) {
//do something
}
}
Try using foreach instead of 尝试使用foreach而不是
this.applicationFormArray.forEach(element => {
if(element.valid) {
//do something
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.