Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Form Arrays in Angular

Form arrays in Angular allow you to manage an array of form controls, enabling dynamic forms where the number of controls can vary based on user interaction. This tutorial covers the basics of creating and using form arrays effectively in your Angular applications.

What are Form Arrays?

Form arrays are instances of the FormArray class that track the value and validity state of an array of FormControl, FormGroup, or even nested FormArray instances. They are particularly useful for handling dynamic forms where the number of form controls is not fixed.

Setting Up Form Arrays

To use form arrays, you need to import the necessary modules and set up your form with FormArray:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, ReactiveFormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

// app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  userForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      phones: this.fb.array([
        this.fb.control('', Validators.required)
      ])
    });
  }

  get phones() {
    return this.userForm.get('phones') as FormArray;
  }

  addPhone() {
    this.phones.push(this.fb.control('', Validators.required));
  }

  removePhone(index: number) {
    this.phones.removeAt(index);
  }

  onSubmit() {
    console.log('Form submitted!', this.userForm.value);
  }
}

// app.component.html
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="name">Name</label>
    <input type="text" id="name" formControlName="name">
    <div *ngIf="userForm.get('name').invalid && userForm.get('name').touched">
      <div *ngIf="userForm.get('name').errors.required">Name is required</div>
    </div>
  </div>
  <div>
    <label for="email">Email</label>
    <input type="email" id="email" formControlName="email">
    <div *ngIf="userForm.get('email').invalid && userForm.get('email').touched">
      <div *ngIf="userForm.get('email').errors.required">Email is required</div>
      <div *ngIf="userForm.get('email').errors.email">Invalid email format</div>
    </div>
  </div>
  <div formArrayName="phones">
    <div *ngFor="let phone of phones.controls; let i = index">
      <label for="phone{{i}}">Phone {{i + 1}}</label>
      <input type="text" [formControlName]="i" id="phone{{i}}">
      <div *ngIf="phone.invalid && phone.touched">
        <div *ngIf="phone.errors.required">Phone number is required</div>
      </div>
      <button type="button" (click)="removePhone(i)">Remove</button>
    </div>
    <button type="button" (click)="addPhone()">Add Phone</button>
  </div>
  <button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>

Key Points

  • Form arrays track the value and validity state of an array of form controls.
  • They are useful for dynamic forms where the number of form controls can vary based on user interaction.
  • You can add and remove form controls from a form array dynamically.
  • Form arrays can contain instances of FormControl, FormGroup, or nested FormArray.
  • Display validation messages conditionally based on the form control's state.

Conclusion

Form arrays in Angular provide a powerful way to manage dynamic forms with variable numbers of form controls. By understanding and using form arrays effectively, you can create flexible and user-friendly forms in your Angular applications. Happy coding!