José Matos
•23 Mar 2023
Building forms in Angular is one of the most common tasks developers have to do. Forms give users a way to input data and interact with an application. However, creating dynamic forms in Angular can be challenging, especially when it comes to handling data from multiple form fields. In this article, we will walk through the process of building dynamic forms using Angular.
Before we jump into building forms, we need to set up our Angular application. First, create a new project using the Angular CLI by running the following command in your terminal:
ng new my-dynamic-forms-app
Once the project is created, navigate to the project directory and install the necessary dependencies by running:
cd my-dynamic-forms-app
npm install --save @angular/forms
Next, we need to create a component that will contain our form. Run the following command in your terminal to generate a new component:
ng g c dynamic-form
This will generate a new component called DynamicFormComponent
. In the DynamicFormComponent
, we need to import the necessary dependencies:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
In the OnInit
method, we will create our form:
ngOnInit() {
this.dynamicForm = new FormGroup({});
}
Now we have an empty form group that we can start adding fields to.
In our DynamicFormComponent
, we will define how our form fields will be generated dynamically. For this example, we will create a simple form that contains two text fields and a dropdown list.
We will create an array of fields that will be rendered dynamically:
fields = [
{ type: 'text', label: 'First Name', name: 'firstName', value: '', required: true, minLength: 3 },
{ type: 'text', label: 'Last Name', name: 'lastName', value: '', required: true, minLength: 3 },
{ type: 'select', label: 'Gender', name: 'gender', value: '', required: true, options: [
{label: 'Male', value: 'male'},
{label: 'Female', value: 'female'}
]}
];
Here, we have defined three fields. The type
property specifies the type of the form field (’text’ or ‘select’). The label
property is used to display a label for the form field. The name
property is used to set the name attribute of the form field. The value
property is used to set the initial value of the field. The required
property indicates if the field is required, and the minLength
property indicates how long the input value should be. Finally, for the dropdown list, the options
property is used to define the list of options.
To dynamically generate the form fields, we will use a ngFor
loop that will iterate over the fields
array:
<div *ngFor="let field of fields">
<label for="{{field.name}}">{{field.label}}</label>
<ng-container [ngSwitch]="field.type">
<input *ngSwitchCase="'text'" type="text" [formControlName]="field.name"
[value]="field.value" [required]="field.required" [minlength]="field.minLength">
<select *ngSwitchCase="'select'" [formControlName]="field.name" [required]="field.required">
<option *ngFor="let option of field.options" [value]="option.value">{{option.label}}</option>
</select>
</ng-container>
</div>
Here, we are using a ngSwitch
directive to switch between the two field types. Depending on the type
property of the field, we will create either a text input or a dropdown list.
Now that we have created our form, we need to submit it and handle the user input. To do this, we will add a submit button to our form and handle its click event:
<button (click)="submitForm()">Submit</button>
And in the DynamicFormComponent
, we will define the submitForm()
method:
submitForm() {
console.log(this.dynamicForm.value);
}
Here, we are simply logging the form values to the console. In a real application, you would typically send the form data to a server or perform some other action.
In addition to submitting the form, we need to ensure that the user input is valid. We can do this by adding validation rules to our form fields.
In our fields
array, we have already defined the validation rules for our fields. Now, we need to add these rules to our form controls. We can do this by creating a FormControl
object for each field and passing the validation rules to it:
ngOnInit() {
let group = {};
this.fields.forEach(field => {
let validators = [];
if (field.required) {
validators.push(Validators.required);
}
if (field.minLength) {
validators.push(Validators.minLength(field.minLength));
}
let control = new FormControl(field.value, validators);
group[field.name] = control;
});
this.dynamicForm = new FormGroup(group);
}
Here, we are creating a new FormControl
for each field in our fields
array. We are adding validators to the control based on the validation rules defined in our fields
array. Finally, we are adding each form control to our form group.
In this article, we have walked through the process of building dynamic forms in Angular. We have seen how to generate form fields dynamically using ngFor
, how to handle form submission and validation, and how to add validation rules to our form fields.
Using these techniques, you can create powerful and flexible forms that can handle the most complex data inputs.