Forms are essential for collecting data. No matter what app you build, you will have to create a form that serves different purposes at some point. With App Builder’s Form Builder, you can streamline the creation of Angular forms through an intuitive drag-and-drop interface and several powerful additional features, ensuring that the creation of forms is faster and more efficient.
But more about this later. Now, let’s look at Forms and explore how App Builder integrates Angular Form Builder to simplify form creation.
Traditionally, creating forms in Angular requires writing boilerplate code to define controls, groups, and validations. However, using Angular Form Builder reduces this manual effort and eliminates errors. Therefore, a Form Builder in Angular is a tool or a separate functionality that provides a more structured way for more straightforward and automated creation of forms while managing the above-mentioned layout configurations, form controls, validations, groups, and more.
Our low-code tool—App Builder™—recently introduced a brand-new feature that provides all these capabilities. Working as an Angular drag-and-drop, Form Builder makes designing HTML forms quick and more efficient, with critical capabilities like auto-generating form structures directly from API endpoints, which take backend integration to another level and simplify the process significantly.
There is also extensive flexibility in form layouts and deep customization with options for displaying notifications for submissions, errors, and server-side validations.
Main aspects of Form Builder:
- Create forms automatically by dragging and dropping an endpoint from your data source
- Modifying components in the form with different equivalents to make your form richer
- Creating a form from scratch
- Testing CRUD capabilities of the created forms
- Generating an Angular app and pushing it to GitHub with production-ready code and complete code flexibility
In Angular apps, FormControl, FormGroup, FormArray, and ControlValueAccessor represent the most fundamental components of Reactive forms. Let’s check each out and try to understand their roles and functionalities.
FormControl
At its core, FormControl is a class in Angular used to track the value and validation status of an individual form field. It also supports synchronous and asynchronous validations. Here are some key points about FormControl:
- Value Tracking: Keeps track of the current value of the form field.
- State Management: Tracks the state (valid, invalid, touched, untouched) of the form field.
- Validation: Supports both synchronous and asynchronous validations.
- Events: Provides access to user interactions and events related to the form field.
Because reactive forms are built on a component class, Angular reactive form validation happens by adding validator functions directly to the form control model in the component class.
When the value is valid, validators return null. If the value is invalid, validators generate a set of errors, and you can display a specific error message on the screen.
The demo below showcases a typical movie booking form using Angular reactive form validation, where required fields—movie, full name, email, and genre—must be completed before submission. Incomplete inputs are highlighted in red with specific error messages, while valid fields turn green. The “Book” button remains disabled until all fields are correctly filled, which activates, allowing successful form submission.
FormGroup
A FormGroup in Angular is a container that aggregates multiple FormControl instances. It tracks the values and validation states of its child form controls, serializing them into an object using their respective names as keys.
FormArray is particularly useful for forms requiring a variable number of similar controls, such as adding multiple email addresses or phone numbers.
Code example of a form where users can input multiple entries, such as email addresses:
import { Component } from '@angular/core';
import { FormGroup, FormArray, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-email-form',
template: \`
<form [formGroup]="form">
<div formArrayName="emails">
<div *ngFor="let email of emailArray.controls; let i = index">
<label for="email-{{ i }}">Email {{ i + 1 }}</label>
<input
id="email-{{ i }}"
type="email"
[formControlName]="i"
placeholder="Enter email"
/>
<button type="button" (click)="removeEmail(i)">Remove</button>
</div>
</div>
<button type="button" (click)="addEmail()">Add Email</button>
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
<p>Form Value: {{ form.value | json }}</p>
\`,
})
export class EmailFormComponent {
form = new FormGroup({
emails: new FormArray([new FormControl('', Validators.email)]),
});
get emailArray(): FormArray {
return this.form.get('emails') as FormArray;
}
addEmail() {
this.emailArray.push(new FormControl('', Validators.email));
}
removeEmail(index: number) {
this.emailArray.removeAt(index);
}
}
Key features include:
- Grouping: Combines multiple FormControl instances into a single object.
- Value Aggregation: Tracks the values of each child control and combines them into an object.
- Validation Management: Manages the validation status of all its child controls.
Here is a code example:
const profileForm = new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl(''),
email: new FormControl('', [Validators.required, Validators.email]),
});
In this code snippet, If any child control is invalid, the entire group is considered invalid.
The FormGroup acts as a container for one or more form controls. It groups related fields together and allows you to collectively manage their values and validation. It is initialized with:
- Default Value: An empty string (”).
- Validators.required: Ensures the component field is not left empty.
What the FormGroup Does in the above example:
- Tracks the Field’s Value: Keeps the current value of datePicker accessible and updatable.
- Manages Validation: Ensures the field is valid before submitting the form.
- Encapsulates Logic: Combines multiple controls into a logical unit, simplifying form management.
FormArray
FormArray is similar to FormGroup, but instead of using names as keys, it organizes controls as an indexed array. This makes it ideal for scenarios where the number of controls is dynamic, such as adding multiple items to a list. Key features include:
- Dynamic Forms: Collects dynamically created forms in a structured array.
- Indexing: Access individual forms using their index in the array.
- Status Aggregation: Calculates the array status by reducing the status values of its children. If one control is invalid, the entire array is considered invalid.
ControlValueAccessor in Angular
ControlValueAccessor is an interface that enables Angular forms to interact with custom form controls, ensuring they behave like standard form elements. When creating custom components that function as form controls (e.g., a custom date picker), implementing ControlValueAccessor allows seamless integration with Angular’s reactive forms.
Here is an example of ControlValueAccessor:
@Component({
selector: 'custom-input',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomInputComponent),
multi: true
}
]
})
export class CustomInputComponent implements ControlValueAccessor {
// Implementation here
}
This setup ensures the custom input component can be used within Angular forms like any native form element. What you get is:
- Seamless Integration: Allows custom components to work with Angular forms.
- Reusability: Enables the creation of reusable form components.
- Consistency: Ensures custom controls adhere to Angular’s form APIs.
Speed and efficiency are essential when building apps today. So, even when it comes to creating forms, teams look for the best way to optimize the results and boost their efforts. Bringing together Angular Form Builder with low code becomes a strategic move that ensures several advantages.
Rapid Form Creation
Manually creating forms and writing code takes much longer than code generation. With the App Builder’s drag-and-drop form-building experience, you have the tools and capabilities to create forms faster without extensive coding. You can easily generate complete forms right from API endpoints, saving significant time and effort.
Full Customization
Apart from speed, you may look for flexibility and customization. The Angular Form Builder in App Builder allows you to tailor styling, components, and form layouts to match the branding and any requirement. There are intuitive configurations to help you add validations, error messages, and other customized enhancements.
Improved Collaboration
Creating forms usually involves designers too who brand the experience. This often leads to prolonged timelines for building forms as teams exchange handoffs and design files for approval and development. However, App Builder and the Angular Form Builder functionality enhance this collaboration as you won’t have to test and debug form structures each time. The intuitive interface ensures simplified design processes with forms that can be easily generated right away. There’s no extensive technical expertise required.
Scalability
Your application may grow, and this requires scalability. The forms built with App Builder’s latest Form Builder functionality are scalable and remain high-performaning across all usage levels. And because there’s no vendor lock-in, you and your team don’t give up the functionality of your apps.
For this how-to guide, we will demonstrate two ways—automatic and manual. We will start with an existing side-by-side layout that very clearly showcases Master Detail scenarios in App Builder. We will have a list of customers and update these customers with the form.
Automatic Form Creation
Step 1: Dragging Data Endpoints
To start, drag a data endpoint onto the design surface. A set of form components will be automatically generated based on the endpoint’s properties.
- POST and PUT methods create input fields for data submission.
- Basic event handling, like OnSuccess and OnError interactions, is configured automatically.
Step 2: Automatic Form Controls Creation and Mapping
Form controls are created based on each field’s data type and metadata, ensuring intuitive inputs and labels (e.g., date fields use date pickers, boolean fields use switches). Developers retain full control to modify components, add validations, or adjust labels directly in the properties panel.
Step 3: Editing the form
Once generated, the form can be modified to include or exclude fields, customize labels, and set input validations, offering an intuitive design experience. App Builder allows developers to tailor both form layout and components:
- Easily add or remove elements within the form.
- Adjust control properties such as Required and Disabled validations, label customization, and mapping.
- Configure action buttons.
Manual Form Creation
You can also build Forms manually in App Builder. The benefit of this approach is that it ensures complete control over the structure and layout without requiring immediate bindings to data sources.
Step 1: Drag and drop elements
This happens by dragging and dropping elements such as input fields, buttons, and form components onto the Form container to design the form.
Step 2: Data Source Binding
Once the form is designed, developers can bind it to an endpoint from configured data sources. This flexibility ensures the ability to refine form elements before defining data interactions.
Step 3: Binding Behavior and Validations
If you switch between endpoints once your form is built, non-matching inputs will display an invalid binding warning, and those bindings will not be generated as broken bindings in the code output. You can also initialize a new variable from the Form endpoint binding dialog with the API data endpoint, giving you the needed context for form initialization.
Invalid bindings are excluded from generated code, ensuring the application compiles without errors. To minimize disruptions when switching endpoints, App Builder provides warnings about potential invalidations.
Conclusion
No matter what approach you choose, in the end, you can use the App Builder’s Preview mode to interact with the form and see real-time input validations or form submissions, with notifications indicating success or validation errors.