在Angular中实现嵌套的formArray需要以下步骤:
1.创建外部formGroup和外部formArray。
export class AppComponent implements OnInit {
form: FormGroup;
externalLineItems: FormArray;
ngOnInit() {
this.externalLineItems = new FormArray([]);
this.form = new FormGroup({
externalLineItems: this.externalLineItems
});
}
}
2.创建内部formArray和内部formGroup。
export class AppComponent implements OnInit {
form: FormGroup;
...
addExternalLineItem() {
(this.form.get('externalLineItems')).push(
new FormGroup({
description: new FormControl(''),
quantity: new FormControl('')
})
);
}
}
3.使用ngFor指令创建外部formArray的表单字段,并通过ng-container嵌套创建内部formArray的表单字段。
4.在内部formGroup中添加内部formArray的表单字段及相应的操作方法。
export class AppComponent implements OnInit {
...
addInternalLineItem(item) {
item.get('internalLineItems').push(
new FormGroup({
description: new FormControl(''),
quantity: new FormControl('')
})
);
}
...
}
使用以上方法,可以在Angular中实现嵌套的formArray。