Building Dynamic Forms in Angular
Tags: angular, javascript, webdev, typescript
Published: 2024-06-04 13:33:11

In Angular applications, forms are a fundamental aspect of collecting and managing user input. While static forms are common, there are scenarios where you need to create dynamic forms that adapt to user interactions, such as adding or removing form fields dynamically. In this article, we’ll explore how to build dynamic forms in Angular using the FormArray class, with step-by-step technical examples

## 1. Importing the FormArray Class

To start building dynamic forms in Angular, we first need to import the FormArray class from the **@angular/forms** module. The **FormArray** class provides us with the tools necessary to manage an array of form controls dynamically.

```
import { FormArray, FormBuilder, ReactiveFormsModule } from '@angular/forms';
```

## 2. Defining a FormArray Control

Next, we define a **FormArray** control within our main **FormGroup**. This FormArray will hold the dynamically added form controls, such as input fields or other form elements.

```
export class ProfileEditorComponent {
  // Initialize FormGroup with FormArray
  profileForm: FormGroup;

  // Constructor to initialize FormBuilder
  constructor(private formBuilder: FormBuilder) {
    this.profileForm = this.formBuilder.group({
      favoriteBooks: this.formBuilder.array([this.formBuilder.control('')])
    });
  }
}
```

## 3. Accessing the FormArray Control

We create a getter method to access the **FormArray** control defined in our **FormGroup**. This getter method allows us to interact with the **FormArray** in our component logic.

```
get favoriteBooks() {
  return this.profileForm.get('favoriteBooks') as FormArray;
}
```
**this.profileForm.get(‘favoriteBooks’)** returns an AbstractControl, but we explicitly cast it to a FormArray using **as FormArray**. Now, whenever we call **this.favoriteBooks**, it will execute this getter method, which in turn retrieves the FormArray control for us.

In essence, the **get favoriteBooks()** method acts as a convenient and consistent way to access the **favoriteBooks** FormArray control within the component. It abstracts away the complexity of accessing the control directly and promotes encapsulation and code readability.

## 3. Displaying the FormArray in the Template

In the HTML template file, we use the formArrayName directive to bind the FormArray to the template. We then use *ngFor to loop through each form control in the FormArray and display the corresponding form fields dynamically.

```
<div formArrayName="favoriteBooks">
  <h2>Favorite Books</h2>
  <button type="button" (click)="addBook()">Add Book</button>
  <div *ngFor="let book of favoriteBooks.controls; let i=index">
    <label for="book-{{ i }}">Book {{ i + 1 }}:</label>
    <input id="book-{{ i }}" type="text" [formControlName]="i">
    <button (click)="removeBook(i)">Delete book </button>
  </div>
</div>
```

## 4. Adding a Method to Dynamically Insert Controls

Now, we implement a method to add new form controls dynamically to the FormArray. This method is called when the user interacts with the form, such as clicking a button to add a new form field.

```
addBook() {
  this.favoriteBooks.push(this.formBuilder.control(''));
}
```

## 5. Adding a Method to Dynamically Delete Controls

Finally, we implement a method to delete a form control. This method is called when the user clicks a button to delete the form field.

```
removeBook(index: number) {
    this.favoriteBooks.removeAt(index)
  }
```

## Conclusion

Dynamic forms provide a flexible and user-friendly way to collect data in Angular applications. By leveraging the FormArray class, developers can create forms that adapt to various user inputs dynamically. With the step-by-step examples provided in this article, you can confidently build dynamic forms in your Angular projects, enhancing the user experience and usability of your applications.

To get the rest of the code check the following links:
[https://github.com/anthony-kigotho/angular-forms](https://github.com/anthony-kigotho/angular-forms)

## CTA
💛If you enjoy my articles, consider [subscribing to my newsletter](https://bytewave.substack.com/) to receive my new articles by email