Saturday, January 12, 2019

Dynamic Forms

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.
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.

Bootstrap

Start by creating an NgModule called AppModule.
This cookbook uses reactive forms.
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.
Bootstrap the AppModule in main.ts.



  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.
The following QuestionBase is a fundamental question class.

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. }

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 supports multiple HTML5 types such as text, email, and url via the type property.

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 presents a list of choices in a select box.

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'] || [];
  }
}

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.

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 is the entry point and the main container for the form.



  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>
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.



  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>
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.
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.
formControlName and formGroup are directives defined in ReactiveFormsModule. The templates can access these directives directly since you imported ReactiveFormsModule from AppModule.

Questionnaire data

DynamicFormComponent expects the list of questions in the form of an array bound to @Input() questions.
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.
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.

src/app/question.service.ts

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

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

app.component.ts

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

Dynamic Template

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.
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

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...