Angular 2 种动态反应形式元素类型

Angular 2 dynamic reactive form element types

我正在根据 https://angular.io/guide/dynamic-form

中的动态表单示例构建表单

除了示例的 'textbox' 和 'dropdown' 之外,我无法找到有关如何设置其他表单元素类型的任何信息。他们的代码示例:

import { QuestionBase } from './question-base';

export class TextboxQuestion extends QuestionBase<string> {
    controlType = 'textbox';
    type: string;

    constructor(options: {} = {}) {
       super(options);
       this.type = options['type'] || '';
    }
}

有一个变量 "controlType" 我认为应该可以取其他值。那里有一些我一直找不到的文档吗?或者是否有其他方法可以将文本区域、复选框或单选按钮添加到动态表单设置中?

您 link 指南中的示例只是让您了解如何创建动态表单。 Angular 没有为此提供现成的解决方案。

这个想法是让您用自己的类型扩展 dynamic-form-question.component.html 模板。这是文本区域的示例:

<div [formGroup]="form">
  <!-- ... -->
  <div [ngSwitch]="question.controlType">

    <!-- Your other types here... -->

    <textarea *ngSwitchCase="'textarea'" [formControlName]="question.key"
                                         [id]="question.key">

  </div> 
  <!-- ... -->
</div>

这将为所有 controlType'textarea' 的动态类型创建一个文本区域元素。 controlType,如您在指南中的示例中所见,只是 属性 基础 class 他们称之为 question-base.ts

textarea class 的简单实现如下所示:

import { QuestionBase } from './question-base';

export class TextareaQuestion extends QuestionBase<string> {
  controlType = 'textarea';

  constructor(options: {} = {}) {
    super(options);
  }
}

然后你只需将它添加到问题数组中,如下所示:

let questions: QuestionBase<any>[] = [
  // ...
  new TextareaQuestion({
    key: 'myTextarea',
    label: 'My textarea!',
    order: 1
  }),
  // ...
]