How to build a dynamic form with Angular — A simple example with explanation

Need a quick intro to dynamic Angular forms?
Here’s a 3-minute guide to get you started.

Dancing in your pants to build a dynamic form with Angular?

Our JSON blob

Here’s the data we’ll be using to dynamically render the form.

“fieldName”: “Name”,
“fieldType”: “text”,
“required”: true
“fieldName”: “Email”,
“fieldType”: “email”,
“required”: true,
“validator”: “email”
“fieldName”: “Message”,
“fieldType”: “text”,
“required”: null

Creating a dynamic Angular form with the JSON response

First we’ll generate a class used to model our form fields and deserialize it nice and sweet.

ng g class form-field
export class FormField {
fieldName: string;
fieldType: string;
required: boolean = false;
validator: string;
import { Component, OnInit } from ‘@angular/core’;
import { HttpClient } from ‘@angular/common/http’
import { FormField } from ‘../form-field’;
import { FormControl, FormGroup, ValidatorFn, Validators } from ‘@angular/forms’;
selector: ‘app-dynamic-form’,
templateUrl: ‘./dynamic-form.component.html’,
styleUrls: [‘./dynamic-form.component.css’]
export class DynamicFormComponent implements OnInit {
formFields: FormField[];
form = new FormGroup({});
private httpClient: HttpClient
) { }
ngOnInit(): void {
this.httpClient.get<FormField[]>(“/assets/form.json”).subscribe((formFields) => {
for (const formField of formFields) {
this.form.addControl(formField.fieldName, new FormControl(‘’,this.getValidator(formField)));
this.formFields = formFields;
onSubmit(): void {
if (this.form.valid) {
let value = this.form.value;
private getValidator(formField: FormField): ValidatorFn {
switch(formField.validator) {
case “email”:
case “required”:
return Validators.required;
return null;
<form [formGroup]=”form” (ngSubmit)=”onSubmit()”>
<div *ngFor=”let formField of formFields” class=”form-group”>
<label> {{ formField.fieldName }}</label>
<input class=”form-control” type=”{{ formField.fieldType }}” value=”{{ formField.fieldName }}” [required]=”formField.required” formControlName=”{{ formField.fieldName }}” />
<button type=”submit” class=”btn btn-primary” [disabled]=”this.form.invalid”>Submit</button>
Dynamic Angular Form


This is a very basic example of how a dynamic form can be created.

Further Reading