动态表单

Dynamic Forms

有时候手动编写和维护表单所需工作量和时间会过大。特别是在需要编写大量表单时。表单都很相似,而且随着业务和监管需求的迅速变化,表单也要随之变化,这样维护的成本过高。

Building handcrafted forms can be costly and time-consuming, especially if you need a great number of them, they're similar to each other, and they change frequently to meet rapidly changing business and regulatory requirements.

基于业务对象模型的元数据,动态创建表单可能会更划算。

It may be more economical to create the forms dynamically, based on metadata that describes the business object model.

本文会展示如何利用 formGroup 来动态渲染一个简单的表单,包括各种控件类型和验证规则。 这个起点很简陋,但可以在这个基础上添加丰富多彩的问卷问题、更优美的渲染以及更卓越的用户体验。

This cookbook shows you how to use formGroup to dynamically render a simple form with different control types and validation. It's a primitive start. It might evolve to support a much richer variety of questions, more graceful rendering, and superior user experience. All such greatness has humble beginnings.

这个例子要为正在找工作的英雄们创建一个在线申请表的动态表单。英雄管理局会不断修改申请流程,你要在不修改应用代码的情况下,动态创建这些表单。

The example in this cookbook is a dynamic form to build an online application experience for heroes seeking employment. The agency is constantly tinkering with the application process. You can create the forms on the fly without changing the application code.

参见在线例子 / 下载范例

See the在线例子 / 下载范例.

启动/引导 (bootstrap)

Bootstrap

从创建一个名叫 AppModuleNgModule 开始。

Start by creating an NgModule called AppModule.

这个烹饪书使用响应式表单

This cookbook uses reactive forms.

响应式表单属于另外一个叫做 ReactiveFormsModuleNgModule,所以,为了使用响应式表单类的指令,你得从 @angular/forms 库中引入 ReactiveFormsModule 模块。

Reactive forms belongs to a different NgModule called ReactiveFormsModule, so in order to access any reactive forms directives, you have to import ReactiveFormsModule from the @angular/forms library.

main.ts 中启动 AppModule

Bootstrap the AppModule in main.ts.

import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { DynamicFormComponent } from './dynamic-form.component'; import { DynamicFormQuestionComponent } from './dynamic-form-question.component'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule ], declarations: [ AppComponent, DynamicFormComponent, DynamicFormQuestionComponent ], bootstrap: [ AppComponent ] }) export class AppModule { constructor() { } }import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule);
      
      
  1. import { BrowserModule } from '@angular/platform-browser';
  2. import { ReactiveFormsModule } from '@angular/forms';
  3. import { NgModule } from '@angular/core';
  4.  
  5. import { AppComponent } from './app.component';
  6. import { DynamicFormComponent } from './dynamic-form.component';
  7. import { DynamicFormQuestionComponent } from './dynamic-form-question.component';
  8.  
  9. @NgModule({
  10. imports: [ BrowserModule, ReactiveFormsModule ],
  11. declarations: [ AppComponent, DynamicFormComponent, DynamicFormQuestionComponent ],
  12. bootstrap: [ AppComponent ]
  13. })
  14. export class AppModule {
  15. constructor() {
  16. }
  17. }

问卷问题模型

Question model

第一步是定义一个对象模型,用来描述所有表单功能需要的场景。英雄的申请流程涉及到一个包含很多问卷问题的表单。问卷问题是最基础的对象模型。

The next step is to define an object model that can describe all scenarios needed by the form functionality. The hero application process involves a form with a lot of questions. The question is the most fundamental object in the model.

下面的 QuestionBase 是最基础的问卷问题基类。

The following QuestionBase is a fundamental question class.

export class QuestionBase<T> { value: T; key: string; label: string; required: boolean; order: number; controlType: string; constructor(options: { value?: T, key?: string, label?: string, required?: boolean, order?: number, controlType?: string } = {}) { this.value = options.value; this.key = options.key || ''; this.label = options.label || ''; this.required = !!options.required; this.order = options.order === undefined ? 1 : options.order; this.controlType = options.controlType || ''; } }
src/app/question-base.ts
      
      
  1. export class QuestionBase<T> {
  2. value: T;
  3. key: string;
  4. label: string;
  5. required: boolean;
  6. order: number;
  7. controlType: string;
  8.  
  9. constructor(options: {
  10. value?: T,
  11. key?: string,
  12. label?: string,
  13. required?: boolean,
  14. order?: number,
  15. controlType?: string
  16. } = {}) {
  17. this.value = options.value;
  18. this.key = options.key || '';
  19. this.label = options.label || '';
  20. this.required = !!options.required;
  21. this.order = options.order === undefined ? 1 : options.order;
  22. this.controlType = options.controlType || '';
  23. }
  24. }

在这个基础上,你派生出两个新类 TextboxQuestionDropdownQuestion,分别代表文本框和下拉框。这么做的初衷是,表单能动态绑定到特定的问卷问题类型,并动态渲染出合适的控件。

From this base you can derive two new classes in TextboxQuestion and DropdownQuestion that represent textbox and dropdown questions. The idea is that the form will be bound to specific question types and render the appropriate controls dynamically.

TextboxQuestion 可以通过 type 属性来支持多种 HTML5 元素类型,比如文本、邮件、网址等。

TextboxQuestion supports multiple HTML5 types such as text, email, and url via the type property.

import { QuestionBase } from './question-base'; export class TextboxQuestion extends QuestionBase<string> { controlType = 'textbox'; type: string; constructor(options: {} = {}) { super(options); this.type = options['type'] || ''; } }
src/app/question-textbox.ts
      
      import { QuestionBase } from './question-base';

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

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

DropdownQuestion 表示一个带可选项列表的选择框。

DropdownQuestion presents a list of choices in a select box.

import { QuestionBase } from './question-base'; export class DropdownQuestion extends QuestionBase<string> { controlType = 'dropdown'; options: {key: string, value: string}[] = []; constructor(options: {} = {}) { super(options); this.options = options['options'] || []; } }
src/app/question-dropdown.ts
      
      import { QuestionBase } from './question-base';

export class DropdownQuestion extends QuestionBase<string> {
  controlType = 'dropdown';
  options: {key: string, value: string}[] = [];

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

接下来定义了 QuestionControlService,一个可以把问卷问题转换为 FormGroup 的服务。 简而言之,这个 FormGroup 使用问卷模型的元数据,并允许你指定默认值和验证规则。

Next is QuestionControlService, a simple service for transforming the questions to a FormGroup. In a nutshell, the form group consumes the metadata from the question model and allows you to specify default values and validation rules.

import { Injectable } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { QuestionBase } from './question-base'; @Injectable() export class QuestionControlService { constructor() { } toFormGroup(questions: QuestionBase<any>[] ) { let group: any = {}; questions.forEach(question => { group[question.key] = question.required ? new FormControl(question.value || '', Validators.required) : new FormControl(question.value || ''); }); return new FormGroup(group); } }
src/app/question-control.service.ts
      
      import { Injectable }   from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

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

@Injectable()
export class QuestionControlService {
  constructor() { }

  toFormGroup(questions: QuestionBase<any>[] ) {
    let group: any = {};

    questions.forEach(question => {
      group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
                                              : new FormControl(question.value || '');
    });
    return new FormGroup(group);
  }
}
    

问卷表单组件

Question form components

现在你已经有一个定义好的完整模型了,接着就可以开始创建一个展现动态表单的组件。

Now that you have defined the complete model you are ready to create components to represent the dynamic form.

DynamicFormComponent 是表单的主要容器和入口点。

DynamicFormComponent is the entry point and the main container for the form.

<div> <form (ngSubmit)="onSubmit()" [formGroup]="form"> <div *ngFor="let question of questions" class="form-row"> <app-question [question]="question" [form]="form"></app-question> </div> <div class="form-row"> <button type="submit" [disabled]="!form.valid">Save</button> </div> </form> <div *ngIf="payLoad" class="form-row"> <strong>Saved the following values</strong><br>{{payLoad}} </div> </div>import { Component, Input, OnInit } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { QuestionBase } from './question-base'; import { QuestionControlService } from './question-control.service'; @Component({ selector: 'app-dynamic-form', templateUrl: './dynamic-form.component.html', providers: [ QuestionControlService ] }) export class DynamicFormComponent implements OnInit { @Input() questions: QuestionBase<any>[] = []; form: FormGroup; payLoad = ''; constructor(private qcs: QuestionControlService) { } ngOnInit() { this.form = this.qcs.toFormGroup(this.questions); } onSubmit() { this.payLoad = JSON.stringify(this.form.value); } }
      
      
  1. <div>
  2. <form (ngSubmit)="onSubmit()" [formGroup]="form">
  3.  
  4. <div *ngFor="let question of questions" class="form-row">
  5. <app-question [question]="question" [form]="form"></app-question>
  6. </div>
  7.  
  8. <div class="form-row">
  9. <button type="submit" [disabled]="!form.valid">Save</button>
  10. </div>
  11. </form>
  12.  
  13. <div *ngIf="payLoad" class="form-row">
  14. <strong>Saved the following values</strong><br>{{payLoad}}
  15. </div>
  16. </div>

它代表了问卷问题列表,每个问题都被绑定到一个 <app-question> 组件元素。 <app-question> 标签匹配到的是组件 DynamicFormQuestionComponent,该组件的职责是根据各个问卷问题对象的值来动态渲染表单控件。

It presents a list of questions, each bound to a <app-question> component element. The <app-question> tag matches the DynamicFormQuestionComponent, the component responsible for rendering the details of each individual question based on values in the data-bound question object.

<div [formGroup]="form"> <label [attr.for]="question.key">{{question.label}}</label> <div [ngSwitch]="question.controlType"> <input *ngSwitchCase="'textbox'" [formControlName]="question.key" [id]="question.key" [type]="question.type"> <select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key"> <option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option> </select> </div> <div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div> </div>import { Component, Input } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { QuestionBase } from './question-base'; @Component({ selector: 'app-question', templateUrl: './dynamic-form-question.component.html' }) export class DynamicFormQuestionComponent { @Input() question: QuestionBase<any>; @Input() form: FormGroup; get isValid() { return this.form.controls[this.question.key].valid; } }
      
      
  1. <div [formGroup]="form">
  2. <label [attr.for]="question.key">{{question.label}}</label>
  3.  
  4. <div [ngSwitch]="question.controlType">
  5.  
  6. <input *ngSwitchCase="'textbox'" [formControlName]="question.key"
  7. [id]="question.key" [type]="question.type">
  8.  
  9. <select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">
  10. <option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>
  11. </select>
  12.  
  13. </div>
  14.  
  15. <div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
  16. </div>

请注意,这个组件能代表模型里的任何问题类型。目前,还只有两种问题类型,但可以添加更多类型。可以用 ngSwitch 决定显示哪种类型的问题。

Notice this component can present any type of question in your model. You only have two types of questions at this point but you can imagine many more. The ngSwitch determines which type of question to display.

在这两个组件中,你依赖 Angular 的 formGroup 来把模板 HTML 和底层控件对象连接起来,该对象从问卷问题模型里获取渲染和验证规则。

In both components you're relying on Angular's formGroup to connect the template HTML to the underlying control objects, populated from the question model with display and validation rules.

formControlNameformGroup 是在 ReactiveFormsModule 中定义的指令。这个模板之所以能使用它们,是因为你曾从 AppModule 中导入了 ReactiveFormsModule

formControlName and formGroup are directives defined in ReactiveFormsModule. The templates can access these directives directly since you imported ReactiveFormsModule from AppModule.

问卷数据

Questionnaire data

DynamicForm 期望得到一个问题列表,该列表被绑定到 @Input() questions 属性。

DynamicFormComponent expects the list of questions in the form of an array bound to @Input() questions.

QuestionService 会返回为工作申请表定义的那组问题列表。在真实的应用程序环境中,你会从数据库里获得这些问题列表。

The set of questions you've defined for the job application is returned from the QuestionService. In a real app you'd retrieve these questions from storage.

关键是,你完全根据 QuestionService 返回的对象来控制英雄的工作申请表。 要维护这份问卷,只要非常简单地添加、修改和删除 questions 数组中的对象就可以了。

The key point is that you control the hero job application questions entirely through the objects returned from QuestionService. Questionnaire maintenance is a simple matter of adding, updating, and removing objects from the questions array.

import { Injectable } from '@angular/core'; import { DropdownQuestion } from './question-dropdown'; import { QuestionBase } from './question-base'; import { TextboxQuestion } from './question-textbox'; @Injectable() export class QuestionService { // TODO: get from a remote source of question metadata // TODO: make asynchronous getQuestions() { let questions: QuestionBase<any>[] = [ new DropdownQuestion({ key: 'brave', label: 'Bravery Rating', options: [ {key: 'solid', value: 'Solid'}, {key: 'great', value: 'Great'}, {key: 'good', value: 'Good'}, {key: 'unproven', value: 'Unproven'} ], order: 3 }), new TextboxQuestion({ key: 'firstName', label: 'First name', value: 'Bombasto', required: true, order: 1 }), new TextboxQuestion({ key: 'emailAddress', label: 'Email', type: 'email', order: 2 }) ]; return questions.sort((a, b) => a.order - b.order); } }
src/app/question.service.ts
      
      
  1. import { Injectable } from '@angular/core';
  2.  
  3. import { DropdownQuestion } from './question-dropdown';
  4. import { QuestionBase } from './question-base';
  5. import { TextboxQuestion } from './question-textbox';
  6.  
  7. @Injectable()
  8. export class QuestionService {
  9.  
  10. // TODO: get from a remote source of question metadata
  11. // TODO: make asynchronous
  12. getQuestions() {
  13.  
  14. let questions: QuestionBase<any>[] = [
  15.  
  16. new DropdownQuestion({
  17. key: 'brave',
  18. label: 'Bravery Rating',
  19. options: [
  20. {key: 'solid', value: 'Solid'},
  21. {key: 'great', value: 'Great'},
  22. {key: 'good', value: 'Good'},
  23. {key: 'unproven', value: 'Unproven'}
  24. ],
  25. order: 3
  26. }),
  27.  
  28. new TextboxQuestion({
  29. key: 'firstName',
  30. label: 'First name',
  31. value: 'Bombasto',
  32. required: true,
  33. order: 1
  34. }),
  35.  
  36. new TextboxQuestion({
  37. key: 'emailAddress',
  38. label: 'Email',
  39. type: 'email',
  40. order: 2
  41. })
  42. ];
  43.  
  44. return questions.sort((a, b) => a.order - b.order);
  45. }
  46. }

最后,在 AppComponent 里显示出表单。

Finally, display an instance of the form in the AppComponent shell.

import { Component } from '@angular/core'; import { QuestionService } from './question.service'; @Component({ selector: 'app-root', template: ` <div> <h2>Job Application for Heroes</h2> <app-dynamic-form [questions]="questions"></app-dynamic-form> </div> `, providers: [QuestionService] }) export class AppComponent { questions: any[]; constructor(service: QuestionService) { this.questions = service.getQuestions(); } }
app.component.ts
      
      
  1. import { Component } from '@angular/core';
  2.  
  3. import { QuestionService } from './question.service';
  4.  
  5. @Component({
  6. selector: 'app-root',
  7. template: `
  8. <div>
  9. <h2>Job Application for Heroes</h2>
  10. <app-dynamic-form [questions]="questions"></app-dynamic-form>
  11. </div>
  12. `,
  13. providers: [QuestionService]
  14. })
  15. export class AppComponent {
  16. questions: any[];
  17.  
  18. constructor(service: QuestionService) {
  19. this.questions = service.getQuestions();
  20. }
  21. }

动态模板

Dynamic Template

在这个例子中,虽然你是在为英雄的工作申请表建模,但是除了 QuestionService 返回的那些对象外,没有其它任何地方是与英雄有关的。

Although in this example you're modelling a job application for heroes, there are no references to any specific hero question outside the objects returned by QuestionService.

这点非常重要,因为只要与问卷对象模型兼容,就可以在任何类型的调查问卷中复用这些组件。 这里的关键是用到元数据的动态数据绑定来渲染表单,对问卷问题没有任何硬性的假设。除控件的元数据外,还可以动态添加验证规则。

This is very important since it allows you to repurpose the components for any type of survey as long as it's compatible with the question object model. The key is the dynamic data binding of metadata used to render the form without making any hardcoded assumptions about specific questions. In addition to control metadata, you are also adding validation dynamically.

表单验证通过之前,保存按钮是禁用的。验证通过后,就可以点击保存按钮,程序会把当前值渲染成 JSON 显示出来。 这表明任何用户输入都被传到了数据模型里。至于如何储存和提取数据则是另一话题了。

The Save button is disabled until the form is in a valid state. When the form is valid, you can click Save and the app renders the current form values as JSON. This proves that any user input is bound back to the data model. Saving and retrieving the data is an exercise for another time.

完整的表单是这样的:

The final form looks like this:

Dynamic-Form

回到顶部

Back to top