【问题标题】:Multi-layer form using Reactive forms in Angular 6在 Angular 6 中使用反应式表单的多层表单
【发布时间】:2019-05-29 16:12:04
【问题描述】:

我正在尝试开发一个 Web 应用程序,它向用户显示一组问题。问题根据类别进行分类。该应用程序是使用 Angular6 开发的。使用后端 REST 服务获取问题。在客户端创建一个接口来模拟 REST 响应结构,该结构具有多个子接口来支持复杂的内部结构。响应将被映射为该接口的List。以下是接口的结构。

我的意图是迭代 List<ICategoryQuestion>,显示带有所有选项的问题,并使用用户选择的选项填充 selectedAnswer

由于我在整个应用程序中都遵循 ReactiveForm 方法,因此我想创建一个具有类似结构的 FormGroup,假设它可以帮助我轻松地将 selectedAnswer 映射回来到列表。这将有助于使用另一个 REST 调用提交问卷,该调用再次接受 List<ICategoryQuestion>

现在真正的挑战是创建一个具有相似结构的 FormGroup。 起初,我创建了一个包含整个 List<ICategoryQuestion> 的 FormGroup。

mainFormGroup: FormGroup = this.formBuilder.group({
   categoryQuestionList: this.formBuilder.array([]);
});

现在我必须获得数组 (categoryQuestionList) 的控制权,然后将类别填充到它。

代码是类似的。

let categoryQuestionListControl = <FormArray> this.mainFormGroup.get("categoryQuestionList");

//iterate the **`List<ICategoryQuestion>`** create a FormGroup //representing each ICategoryQuestion and push it to the `categoryQuestionListControl`.

iterate list{
    categoryQuestionListControl.push(this.getCategoryQuestionFormGroup(categoryQuestion));
}

现在 categoryQuestionFormGroup 有一个 List&lt;IQuestionAnswer&gt;,它内部又包含一个 IOptions 数组,这会使代码更加复杂。

您认为处理此类情况的理想方式是什么?我想在这里使用 模板驱动 方法吗?我什至怀疑我是否遵循正确的方法,因为我是 Angulat 2+ 的新手。

请多多指教。

【问题讨论】:

  • 等等,“填充 selectedAnswer”是指你有问题和答案吗?您想使用用户之前选择的答案重新创建问题吗?
  • Selectedanswer 只是用户选择的“选项”的副本

标签: angular typescript angular-reactive-forms angular-template-form


【解决方案1】:

我认为表单组是不必要的,您可以在主控制器上控制最终的问卷,就像向导模式一样。 我的方式是:

let Categories = [{...},...];
let selectedCategory = null;
let categoryQuestions = null;
let questionnaire = null;
wizardManager() {
  if (! selectedCategory) {
    do step1 //popup window allow user choose category, then fill selectedCategory, CategoryQuestions and init questionnaire = {categoryId: id, answers:[]}
  else if (questionnaire.answers.length != categoryQuestions.length) {
    let question = categoryQuestions[questionnaire.answers.length];
    repeat step2 //popup window show question and answers, then save answer to questionnaire.answers
  } else {
    All question answered, submit it.
  }
}
init() {
  wizardManager();
}
popupWindow() {
  openModal, and let modal call wizardManager onDismiss
}

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多