【发布时间】:2018-06-22 11:42:28
【问题描述】:
我目前正在为一个项目使用 Angular Reactive 表单 - 它是一种动态表单,无法真正建模,因为它的属性会随着时间而改变。现在它是一个高度嵌套的表单,它包含多达 4-5 层的深度。
现在我有一个主/外部 FormGroup,它包含一个具有属性的“脚本”的 FormArray 和一个“问题”的 FormArray。 Questions 具有 FormArray 为“Fields”的属性。字段具有属性以及这些字段的另一个 FormArray 选项。并非所有的“字段”都有单行文本等选项,但下拉字段会有。
它从 CosmosDB 获取一个 Document 对象并对其进行迭代,基本上构建了 FormGroup...我的问题是因为这看起来很混乱,我很想知道是否有更好的方法来实现这一点。
这是一个文档示例
"ScriptType": "Script",
"Questions": [
{
"Question": "What is the year, make and model of the vehicle your calling about?",
"Type": "question",
"Text": "",
"Fields": [
{
"PropertyName": "VehicleYear",
"Label": "Year",
"IsRequired": false,
"Type": "drop-down",
"HasOptions": false,
"Options": [2001, 2002, 2003, ...]
},
{
"PropertyName": "VehicleMake",
"Label": "Make",
"IsRequired": false,
"Type": "single-line-text",
"HasOptions": false,
"Options": []
}
下面是当前初始化表单的Angular组件...
initScript(script) {
const scriptGroup = this.fb.group({
ScriptID: script.ScriptID || '',
ScriptType: script.ScriptType,
ScriptName: script.ScriptName,
ScriptText: script.ScriptText,
Questions: this.fb.array([])
});
const scriptControl = scriptGroup.get('Questions') as FormArray;
script.Questions.forEach(element => {
scriptControl.push(this.initQuestion(element));
});
return scriptGroup;
}
initQuestion(script) {
const questionGroup = this.fb.group({
Question: script.Question || '',
Type: script.Type || '',
Fields: this.fb.array([script.Fields] || []),
IsVisible: script.IsVisible || true,
Rules: [script.Rules] || []
});
const fieldControl = questionGroup.get('Fields') as FormArray;
script.Fields.forEach(element => {
fieldControl.push(this.initField(element));
});
return questionGroup;
initField(script) {
return this.fb.group({
PopertyName: script.PropertyName || '',
PropertyName: script.PropertyName || '',
Label: script.Label || '',
Type: script.Type || '',
Options: [script.Options] || []
});
}
随着时间的推移可能会有数百个这样的控件,因此在前端访问这些控件也有点麻烦,而且嵌套如此之多。此外,一旦提交新表单,也需要保存对这些“问题”的响应。如果有人有任何建议,请告诉我!谢谢
【问题讨论】:
标签: angular5 angular-reactive-forms