multimediamike
multimediamike

Reputation: 15

Angular 2 dynamic reactive form element types

I am building a form based upon the dynamic form example at https://angular.io/guide/dynamic-form

I have not been able to find any information on how to set up other form element types beside the example's 'textbox' and 'dropdown'. Their code sample:

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

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

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

has a variable "controlType" that I would think should be able to take other values. Is there some documentation of it out there that I just haven't been able to find? Or are there alternate ways of adding in textareas, checkboxes, or radio buttons to the dynamic form setup?

Upvotes: 1

Views: 590

Answers (1)

Fredrik Lundin Grande
Fredrik Lundin Grande

Reputation: 8186

The example in the guide you link to is just giving you the concept of how you can create a dynamic form. Angular doesn't provide a ready solution for this.

The idea is for you to extend the dynamic-form-question.component.html template with your own types. Here is an example of a text area:

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

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

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

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

That would create a textarea element for all your dynamic types with a controlType of 'textarea'. controlType, as you see in the example in the guide, is just a property on the base class they call question-base.ts

A simple implementation of the textarea class could look like this:

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

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

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

And then you would just add it to the questions array like this:

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

Upvotes: 1

Related Questions