在Angular中,使用反应式表单可以轻松地填充嵌套的formArray。下面是一个示例代码,展示了如何填充嵌套的formArray。
首先,你需要在组件类中创建一个反应式表单,并初始化formArray。在这个示例中,我们将创建一个嵌套的formArray,其中包含多个嵌套的formGroup。
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
nestedForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.nestedForm = this.fb.group({
nestedArray: this.fb.array([]) // 初始化嵌套的formArray
});
// 添加一个初始的嵌套的formGroup
const initialGroup = this.fb.group({
name: '',
age: ''
});
this.nestedArray.push(initialGroup);
}
// 获取嵌套的formArray
get nestedArray() {
return this.nestedForm.get('nestedArray') as FormArray;
}
// 添加新的嵌套的formGroup
addGroup() {
const newGroup = this.fb.group({
name: '',
age: ''
});
this.nestedArray.push(newGroup);
}
// 移除指定的嵌套的formGroup
removeGroup(index: number) {
this.nestedArray.removeAt(index);
}
// 提交表单
submitForm() {
console.log(this.nestedForm.value);
}
}
在模板中,你可以使用formArrayName
和formGroupName
指令来处理嵌套的formArray和formGroup。
在上面的示例中,我们创建了一个初始的嵌套的formGroup,并使用ngFor
指令在模板中循环显示嵌套的formGroup。在每个嵌套的formGroup中,我们使用formControlName
指令来绑定输入字段的值。
通过添加addgroup()
方法,可以在点击“Add Group”按钮时动态地向嵌套的formArray中添加一个新的formGroup。类似地,removeGroup()
方法用于从指定的位置删除嵌套的formGroup。
最后,submitForm()
方法用于在提交表单时打印出嵌套表单的值。
这就是使用Angular反应式表单填充嵌套的formArray的解决方法。
下一篇:Angular反应式验证