{ "id": "guide/dynamic-form", "title": "Building dynamic forms", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Building dynamic formslink

\n

Many forms, such as questionaires, can be very similar to one another in format and intent.\nTo make it faster and easier to generate different versions of such a form,\nyou can create a dynamic form template based on metadata that describes the business object model.\nYou can then use the template to generate new forms automatically, according to changes in the data model.

\n

The technique is particularly useful when you have a type of form whose content must\nchange frequently to meet rapidly changing business and regulatory requirements.\nA typical use case is a questionaire. You might need to get input from users in different contexts.\nThe format and style of the forms a user sees should remain constant, while the actual questions you need to ask vary with the context.

\n

In this tutorial you will build a dynamic form that presents a basic questionaire.\nYou will build an online application for heroes seeking employment.\nThe agency is constantly tinkering with the application process, but by using the dynamic form\nyou can create the new forms on the fly without changing the application code.

\n

The tutorial walks you through the following steps.

\n
    \n
  1. Enable reactive forms for a project.
  2. \n
  3. Establish a data model to represent form controls.
  4. \n
  5. Populate the model with sample data.
  6. \n
  7. Develop a component to create form controls dynamically.
  8. \n
\n

The form you create uses input validation and styling to improve the user experience.\nIt has a Submit button that is only enabled when all user input is valid, and flags invalid input with color coding and error messages.

\n

The basic version can evolve to support a richer variety of questions, more graceful rendering, and superior user experience.

\n
\n

See the .

\n
\n

Prerequisiteslink

\n

Before doing this tutorial, you should have a basic understanding to the following.

\n\n

Enable reactive forms for your projectlink

\n

Dynamic forms are based on reactive forms. To give the application access reactive forms directives, the root module imports ReactiveFormsModule from the @angular/forms library.

\n

The following code from the example shows the setup in the root module.

\n\n\n \nimport { BrowserModule } from '@angular/platform-browser';\nimport { ReactiveFormsModule } from '@angular/forms';\nimport { NgModule } from '@angular/core';\n\nimport { AppComponent } from './app.component';\nimport { DynamicFormComponent } from './dynamic-form.component';\nimport { DynamicFormQuestionComponent } from './dynamic-form-question.component';\n\n@NgModule({\n imports: [ BrowserModule, ReactiveFormsModule ],\n declarations: [ AppComponent, DynamicFormComponent, DynamicFormQuestionComponent ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule {\n constructor() {\n }\n}\n\n\n\n\n \nimport { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nimport { AppModule } from './app/app.module';\nimport { environment } from './environments/environment';\n\nif (environment.production) {\n enableProdMode();\n}\n\nplatformBrowserDynamic().bootstrapModule(AppModule);\n\n\n\n\n\n\n

Create a form object modellink

\n

A dynamic form requires an object model that can describe all scenarios needed by the form functionality.\nThe example hero-application form is a set of questions—that is, each control in the form must ask a question and accept an answer.

\n

The data model for this type of form must represent a question.\nThe example includes the DynamicFormQuestionComponent, which defines a question as the fundamental object in the model.

\n

The following QuestionBase is a base class for a set of controls that can represent the question and its answer in the form.

\n\nexport class QuestionBase<T> {\n value: T;\n key: string;\n label: string;\n required: boolean;\n order: number;\n controlType: string;\n type: string;\n options: {key: string, value: string}[];\n\n constructor(options: {\n value?: T;\n key?: string;\n label?: string;\n required?: boolean;\n order?: number;\n controlType?: string;\n type?: string;\n options?: {key: string, value: string}[];\n } = {}) {\n this.value = options.value;\n this.key = options.key || '';\n this.label = options.label || '';\n this.required = !!options.required;\n this.order = options.order === undefined ? 1 : options.order;\n this.controlType = options.controlType || '';\n this.type = options.type || '';\n this.options = options.options || [];\n }\n}\n\n\n\n

Define control classeslink

\n

From this base, the example derives two new classes, TextboxQuestion and DropdownQuestion,\nthat represent different control types.\nWhen you create the form template in the next step, you will instantiate these specific question types in order to render the appropriate controls dynamically.

\n\n

Compose form groupslink

\n

A dynamic form uses a service to create grouped sets of input controls, based on the form model.\nThe following QuestionControlService collects a set of FormGroup instances that consume the metadata from the question model. You can specify default values and validation rules.

\n\nimport { Injectable } from '@angular/core';\nimport { FormControl, FormGroup, Validators } from '@angular/forms';\n\nimport { QuestionBase } from './question-base';\n\n@Injectable()\nexport class QuestionControlService {\n constructor() { }\n\n toFormGroup(questions: QuestionBase<string>[] ) {\n const group: any = {};\n\n questions.forEach(question => {\n group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)\n : new FormControl(question.value || '');\n });\n return new FormGroup(group);\n }\n}\n\n\n\n\n

Compose dynamic form contentslink

\n

The dynamic form itself will be represented by a container component, which you will add in a later step.\nEach question is represented in the form component's template by an <app-question> tag, which matches an instance of DynamicFormQuestionComponent.

\n

The DynamicFormQuestionComponent is responsible for rendering the details of an individual question based on values in the data-bound question object.\nThe form relies on a [formGroup] directive to connect the template HTML to the underlying control objects.\nThe DynamicFormQuestionComponent creates form groups and populates them with controls defined in the question model, specifying display and validation rules.

\n\n\n \n<div [formGroup]=\"form\">\n <label [attr.for]=\"question.key\">{{question.label}}</label>\n\n <div [ngSwitch]=\"question.controlType\">\n\n <input *ngSwitchCase=\"'textbox'\" [formControlName]=\"question.key\"\n [id]=\"question.key\" [type]=\"question.type\">\n\n <select [id]=\"question.key\" *ngSwitchCase=\"'dropdown'\" [formControlName]=\"question.key\">\n <option *ngFor=\"let opt of question.options\" [value]=\"opt.key\">{{opt.value}}</option>\n </select>\n\n </div>\n\n <div class=\"errorMessage\" *ngIf=\"!isValid\">{{question.label}} is required</div>\n</div>\n\n\n\n\n \nimport { Component, Input } from '@angular/core';\nimport { FormGroup } from '@angular/forms';\n\nimport { QuestionBase } from './question-base';\n\n@Component({\n selector: 'app-question',\n templateUrl: './dynamic-form-question.component.html'\n})\nexport class DynamicFormQuestionComponent {\n @Input() question: QuestionBase<string>;\n @Input() form: FormGroup;\n get isValid() { return this.form.controls[this.question.key].valid; }\n}\n\n\n\n\n\n

The goal of the DynamicFormQuestionComponent is to present question types defined in your model.\nYou only have two types of questions at this point but you can imagine many more.\nThe ngSwitch statement in the template determines which type of question to display.\nThe switch uses directives with the formControlName and formGroup selectors. Both directives are defined in ReactiveFormsModule.

\n\n

Supply datalink

\n

Another service is needed to supply a specific set of questions from which to build an individual form.\nFor this exercise you will create the QuestionService to supply this array of questions from the hard-coded sample data.\nIn a real-world app, the service might fetch data from a backend system.\nThe key point, however, is that you control the hero job-application questions entirely through the objects returned from QuestionService.\nTo maintain the questionnaire as requirements change, you only need to add, update, and remove objects from the questions array.

\n

The QuestionService supplies a set of questions in the form of an array bound to @Input() questions.

\n\nimport { Injectable } from '@angular/core';\n\nimport { DropdownQuestion } from './question-dropdown';\nimport { QuestionBase } from './question-base';\nimport { TextboxQuestion } from './question-textbox';\nimport { of } from 'rxjs';\n\n@Injectable()\nexport class QuestionService {\n\n // TODO: get from a remote source of question metadata\n getQuestions() {\n\n const questions: QuestionBase<string>[] = [\n\n new DropdownQuestion({\n key: 'brave',\n label: 'Bravery Rating',\n options: [\n {key: 'solid', value: 'Solid'},\n {key: 'great', value: 'Great'},\n {key: 'good', value: 'Good'},\n {key: 'unproven', value: 'Unproven'}\n ],\n order: 3\n }),\n\n new TextboxQuestion({\n key: 'firstName',\n label: 'First name',\n value: 'Bombasto',\n required: true,\n order: 1\n }),\n\n new TextboxQuestion({\n key: 'emailAddress',\n label: 'Email',\n type: 'email',\n order: 2\n })\n ];\n\n return of(questions.sort((a, b) => a.order - b.order));\n }\n}\n\n\n\n\n

Create a dynamic form templatelink

\n

The DynamicFormComponent component is the entry point and the main container for the form, which is represented using the <app-dynamic-form> in a template.

\n

The DynamicFormComponent component presents a list of questions by binding each one to an <app-question> element that matches the DynamicFormQuestionComponent.

\n\n\n \n<div>\n <form (ngSubmit)=\"onSubmit()\" [formGroup]=\"form\">\n\n <div *ngFor=\"let question of questions\" class=\"form-row\">\n <app-question [question]=\"question\" [form]=\"form\"></app-question>\n </div>\n\n <div class=\"form-row\">\n <button type=\"submit\" [disabled]=\"!form.valid\">Save</button>\n </div>\n </form>\n\n <div *ngIf=\"payLoad\" class=\"form-row\">\n <strong>Saved the following values</strong><br>{{payLoad}}\n </div>\n</div>\n\n\n\n\n \nimport { Component, Input, OnInit } from '@angular/core';\nimport { FormGroup } from '@angular/forms';\n\nimport { QuestionBase } from './question-base';\nimport { QuestionControlService } from './question-control.service';\n\n@Component({\n selector: 'app-dynamic-form',\n templateUrl: './dynamic-form.component.html',\n providers: [ QuestionControlService ]\n})\nexport class DynamicFormComponent implements OnInit {\n\n @Input() questions: QuestionBase<string>[] = [];\n form: FormGroup;\n payLoad = '';\n\n constructor(private qcs: QuestionControlService) { }\n\n ngOnInit() {\n this.form = this.qcs.toFormGroup(this.questions);\n }\n\n onSubmit() {\n this.payLoad = JSON.stringify(this.form.getRawValue());\n }\n}\n\n\n\n\n\n

Display the formlink

\n

To display an instance of the dynamic form, the AppComponent shell template passes the questions array returned by the QuestionService to the form container component, <app-dynamic-form>.

\n\nimport { Component } from '@angular/core';\n\nimport { QuestionService } from './question.service';\nimport { QuestionBase } from './question-base';\nimport { Observable } from 'rxjs';\n\n@Component({\n selector: 'app-root',\n template: `\n <div>\n <h2>Job Application for Heroes</h2>\n <app-dynamic-form [questions]=\"questions$ | async\"></app-dynamic-form>\n </div>\n `,\n providers: [QuestionService]\n})\nexport class AppComponent {\n questions$: Observable<QuestionBase<any>[]>;\n\n constructor(service: QuestionService) {\n this.questions$ = service.getQuestions();\n }\n}\n\n\n\n

The example provides a model for a job application for heroes, but there are\nno references to any specific hero question other than the objects returned by QuestionService.\nThis separation of model and data allows you to repurpose the components for any type of survey\nas long as it's compatible with the question object model.

\n

Ensuring valid datalink

\n

The form template uses dynamic data binding of metadata to render the form\nwithout making any hardcoded assumptions about specific questions.\nIt adds both control metadata and validation criteria dynamically.

\n

To ensure valid input, the Save button is disabled until the form is in a valid state.\nWhen the form is valid, you can click Save and the app renders the current form values as JSON.

\n

The following figure shows the final form.

\n
\n \"Dynamic-Form\"\n
\n

Next stepslink

\n\n\n \n
\n\n\n" }