我正在为我的API构建Web客户端,我正在使用Angular 5/6。我还没有完成API,所以我可以在模型中进行一些更改。在我的预览客户端中,我使用的是模板驱动的表单,但现在我正在尝试使用响应式表单,因为验证和可测试性。我的问题是嵌套的表单/组件,我决定使用嵌套模型传递请求:
{
"id": 1,
...
"documents": [
{"id":1 ... items:[{"id":1},{"id":2},{"id":3}]},
{"id":2 ... items:[]},
{"id":3 ... items:[{"id":1},{"id":2}]},
]
}
我应该使用一个嵌套形式的组件:
formGroup: FormGroup;
itemFormGroup: FormGroup;
docFormGroup: FormGroup;
constructor(private fb: FormBuilder) { }
createForm = () => {
this.formGroup = this.fb.group({
id: [0, [Validations.required]],
...
documents: this.fb.array([])
});
}
createDocumentForm = () => {
this.docFormGroup = this.fb.group({
id: [0, [Validations.required]],
...
items: this.fb.array([])
});
}
createItemForm = () => {
this.itemFormGroup = this.fb.group({
id: [0, [Validations.required]],
...
});
}
addDocuent = () => {
const control = <FormArray>this.formGroup.get('documents').value;
control.push(this.docFormGroup);
}
addItem = () => {
const control = <FormArray>this.formGroup.get('items').value; // by docID ofc.
control.push(this.itemFormGroup);
}
或者我应该为每一层切割组件并使用@ Input / @ Output prop来传递此表单。
我尝试了两种方法,但第一段代码很难阅读和管理。使用第二种方法,我不确定是否应该将FormArray与输入/输出一起传递给文档列表组件,如果从项目组件传递FormGroup或从API传递对象,并且在每个层构造上新的表单取决于需求?
我决定使用嵌套模型,因为我不需要先发布父级并等待其ID来保存子级,并且获取请求我确定我的子对象状态不变。
我将非常感谢使用模型驱动/反应式表单app处理复杂/嵌套模型的一些代码示例。