Form Generator with Angular 12

Author: Taco Dankers

Inquiry forms and questionnaires need to be flexible and are depending on the business requirements. With a form generator, a form can easily be adjusted or extended without the help of a programmer.

Form-generator is a simple example that implements a generator and creates a form from a JSON array. This simple example generator has only two input types, a check-box and a text field.

The steps

  1. Generate the application with “ng new form-generator”

2. Create a JSON array with the form elements, we use a constant array, but you can also provide the JSON array through an API call from a backend.

3. Create an Angular class, that is called “FormElement”, this class represent the individual form element.

4. Create a parent component “master-form” that contains the top Form element and the logic to create the form and return the response.

5. Create the child components that represent the individual input fields. These components only need a property “FormElement”. We can remove the constructor and ngOnInit function. The HTML template contains the input field. The containing <div> element has a reference to the “master” formGroup and the <input> field contains a “formControlName”. The “formGroup” and “formControlname” ties the elements to the reactive master form.

a. Component “master-form

b. Component: “text-box

c. Component: “check-box

6. Use our under step 2 created JSON array to populate an array with the “FormElement” classes and add for every “FormElement” a FormControl to the FormGroup. The JSON object, FormElement and FormControl are tied together by a unique “id”

That is all. You can find the whole project at GitHub tdankers/form-generator