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?

[
{
“fieldName”: “Name”,
“fieldType”: “text”,
“required”: true
},
{
“fieldName”: “Email”,
“fieldType”: “email”,
“required”: true,
“validator”: “email”
},
{
“fieldName”: “Message”,
“fieldType”: “text”,
“required”: null
}
]
Image for post
Image for post

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’;
@Component({
selector: ‘app-dynamic-form’,
templateUrl: ‘./dynamic-form.component.html’,
styleUrls: [‘./dynamic-form.component.css’]
})
export class DynamicFormComponent implements OnInit {
formFields: FormField[];
form = new FormGroup({});
constructor(
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”:
return Validators.email;
case “required”:
return Validators.required;
default:
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 }}” />
<br>
</div>
<button type=”submit” class=”btn btn-primary” [disabled]=”this.form.invalid”>Submit</button>
</form>
Image for post
Image for post
Dynamic Angular Form

Conclusion

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

Image for post
Image for post

Further Reading

- https://angular.io/guide/dynamic-form

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store