Blog>
Snippets

FormArray with Custom Components

Create an example of how to use FormArray within Angular to handle an array of custom component instances within a form.
import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
Import necessary Angular core components along with FormBuilder and FormArray utilities.
// CustomComponent is a placeholder for your custom input component.
// It should be implemented elsewhere in your project.
import { CustomComponent } from './custom.component';
Import the custom component that will be used within the form array.
@Component({
  selector: 'app-custom-form-array',
  templateUrl: './custom-form-array.component.html'
})
export class CustomFormArrayComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      // Initialize the FormArray with an empty array
      customComponents: this.fb.array([])
    });
  }

  get customComponents(): FormArray {
    return this.myForm.get('customComponents') as FormArray;
  }

  // Adds a new instance of the CustomComponent to the FormArray
  addCustomComponent(): void {
    this.customComponents.push(this.fb.group({
      // Your custom component's form controls
      customField: ['']
    }));
  }

  // Removes an instance of the CustomComponent from the FormArray
  removeCustomComponent(index: number): void {
    this.customComponents.removeAt(index);
  }

}
Define an Angular component with a FormArray that holds instances of a FormGroup representing the custom component. This allows adding and removing components dynamically.
<!-- custom-form-array.component.html -->
<form [formGroup]="myForm">
  <div formArrayName="customComponents">
    <div *ngFor="let control of customComponents.controls; let i = index" [formGroupName]="i">
      <!-- Include the custom component and bind its form control -->
      <app-custom-component formControlName="customField"></app-custom-component>
      <button (click)="removeCustomComponent(i)">Remove</button>
    </div>
  </div>
  <button (click)="addCustomComponent()">Add Component</button>
</form>
The HTML template for the Angular component that includes the FormArray. It uses *ngFor to loop over the FormArray controls, renders the custom component, and provides buttons to add or remove components.