在Angular中,深层嵌套的响应式表单可以使用FormArray来实现。但有时候,在嵌套的FormArray中找不到指定路径的控件可能会引发错误。下面是解决此问题的一种方法。
首先,确保你正确设置了嵌套的FormArray和FormGroup。例如,假设你有一个嵌套的表单,其中包含一个FormArray,每个FormArray中有一个FormGroup,每个FormGroup中有一个FormControl。你可以按照以下方式设置表单:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-nested-form',
template: `
`,
})
export class NestedFormComponent {
nestedForm: FormGroup;
constructor(private fb: FormBuilder) {
this.nestedForm = this.fb.group({
nestedArray: this.fb.array([
this.fb.group({
control: ['']
})
])
});
}
submitForm() {
console.log(this.nestedForm.value);
}
}
然后,要访问FormArray中的控件,你可以使用get方法,该方法接受一个路径参数。路径参数是一个字符串数组,用于指定要访问的控件的路径。例如,要访问第一个FormGroup中的control控件,你可以使用以下代码:
const control = this.nestedForm.get('nestedArray.0.control');
如果在嵌套的FormArray中找不到指定路径的控件,可能是路径不正确。请确保路径中的每个级别都正确,并且没有拼写错误。