在Angular中,可以使用FormArray来处理表单数组模型。下面是一个示例解决方法:
首先,在组件中导入必要的模块和类:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';
然后,在组件类中定义一个表单组:
@Component({
selector: 'app-form-array',
template: `
`
})
export class FormArrayComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.myForm.get('items') as FormArray;
}
addItem() {
const itemFormGroup = this.fb.group({
name: '',
quantity: ''
});
this.items.push(itemFormGroup);
}
removeItem(index: number) {
this.items.removeAt(index);
}
onSubmit() {
console.log(this.myForm.value);
}
}
在上述代码中,我们首先使用FormBuilder创建了一个名为myForm的表单组,并在其中创建了一个名为items的FormArray。
在HTML模板中,我们使用formArrayName指令来关联items表单数组,并使用*ngFor循环遍历items.controls中的每个控件。然后,使用formGroupName指令关联每个控件的索引。
通过使用formControlName指令,我们可以将输入元素与表单控件进行绑定,并通过调用addItem和removeItem方法来动态添加和删除表单项。
最后,在onSubmit方法中,我们可以通过访问myForm.value来获取表单数据。
希望以上示例能帮助到您!