...

/

Build Dynamic Forms from a Backend Config File

Build Dynamic Forms from a Backend Config File

Leverage the full potential of reactive form APIs using dynamic configurations to craft forms on the fly.

At this point of the course, we should already have a solid understanding of Angular reactive forms and how to use them in the best way in our projects. However, we’re still missing a particular scenario to master them entirely.

The previous examples provided all the necessary details about the form model. In some cases, like in the previous lesson, we didn’t know how many form sections would have been necessary. For instance, the number of addresses a user might need to register. Nevertheless, even the form sections added at runtime had a preconfigured set of fields and validation rules. However, what could we do if the form should be tailored according to determined conditions?

For instance, our application might require changing the registration form according to the user role, her account type, or when the form fields often change, like in the case of an exam questionnaire.

According to business logic rules, the server delivers a configuration file to the client that would shape the form accordingly. This approach is highly flexible because form fields or validation rules can be defined in a database. If anything needs to be changed, we need to modify the form configuration in the database without needing a new deployment or changing the client application. This might sound like a bizarre requirement, but it occurs more often than we think, especially in complex and big projects.plex and big projects.

Create fully dynamic forms

Different aspects must be adjusted before being able to create dynamic forms tailored from a configuration file delivered from a server API. The following chapters will decompose each of these aspects and describe all the involved passages in detail.

Design the form model

First of all, we need to design a generic form model. We have to look at this kind of model from a higher and more abstract point of view because it will cover all possible form values necessary in the application.

Press + to interact
export interface SelectOptions {
key: string | number;
value: string;
}
export enum FormFieldType {
text = 'Text',
select = 'Select',
checkbox = 'Checkbox',
}
export interface FormFieldConfig {
fieldId: string;
type: FormFieldType;
label?: string;
value?: string | boolean | number;
// Options is used for drop-down elements
options?: SelectOptions[];
// State flags
disabled?: boolean;
required?: boolean;
}

Lines 1–4: The SelectedOption interface determines the type for select elements. In the code snippet above, ...