Dynamic forms in Angular can be a great solution for form heavy web apps. Each control can be defined by an object and placed in an array to compose the form, providing a quick and easy way to stamp out complex forms.

I have created this example project that implements a dynamic form solution, it has added complexities such as VisibleIf, DisabledIf and RequiredIf properties which respectively provide a way to conditionally display, require and disable a control based on the values of other controls within the form.

A control object may be defined like so:

new InputControl ({
    key: 'username',
    placeholder: 'Username',
    type: 'text',
    required: true,
    value: ''
}),

This creates a required input control, the key is used as a reference, the other properties map to a HTML matInput field. The control would be defined alongside other controls in an array, and the array would be passed to the dynamic form component as an input

form = [
    new InputControl ({
        key: 'username',
        placeholder: 'Username',
        type: 'text',
        required: true,
        value: ''
    }),
    new InputControl ({
        key: 'email',
        placeholder: 'Email',
        type: 'text',
        visibleIf: [
        {
            username: (value: string) => value && value.length > 0
        }
        ],
        requiredIf: [
        {
            newsletterOptIn: (value: boolean) => value
        }
      ]
    }),
    new CheckboxControl({
        key: 'newsletterOptIn',
        placeholder: 'Opt in to our news letter?',
        visibleIf: [
        {
            username: (value: string) => value && value.length > 0,
        }
        ]
    }),
    new InputControl ({
        key: 'phone',
        placeholder: 'Phone',
        type: 'text',
        required: false,
        value: '',
        visibleIf: [
          {
            username: (value: string) => value && value.length > 0,
            email: (value: string) => value && value.length > 0
          }
        ]
      })
]

This array would generate a form with four fields:

Screenshot of how the form would look
The former code example rendered. The email is required but not set.

A more complete write up can be found in the README for the project.