【问题标题】:Dynamic Angular 5 Nested Reactive FormsDynamic Angular 5 嵌套响应式表单
【发布时间】: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


    【解决方案1】:

    好的,不确定是否完全理解,但请参阅此处示例如何动态创建这些字段。您还可以根据从后端加载的 JSON 生成它们。

    https://stackblitz.com/edit/angular-reactive-form-sobsoft

    【讨论】:

    • 请感谢您的回答..您知道为什么我按照这些步骤操作后会出现此错误吗? “AbstractControl”类型上不存在属性“控件”。 30 *ngFor="让exampleForm.controls.units.controls的单位;让i=index"
    猜你喜欢
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多