我目前正在为项目使用Angular Reactive表单 - 它是一个无法真正建模的动态表单,因为它上面的属性会随着时间的推移而改变。现在它是一个高度嵌套的形式,内置多达4-5级深。
现在我有一个主/外FormGroup,它包含一个FormArray的'Scripts',它具有属性和FormArray的'Questions'。问题具有FormArray为“Fields”的属性。 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] || []
});
}
随着时间的推移,可能有数百个,所以在前端访问这些控件有点麻烦,因此也是如此嵌套。此外,一旦提交新表格,也需要保存对这些“问题”的回复。如果有人有任何建议,请告诉我!感谢
答案 0 :(得分:1)
确定无法完全理解,但请参见此处示例如何动态创建这些字段。您还可以基于从后端加载的JSON生成它们。