📝 Reactive Forms

Type-safe forms with FormBuilder, validation, and dynamic FormArray

About This Feature

Angular's Reactive Forms are defined in the component class using FormBuilder. They provide a model-driven approach where form state is managed programmatically, offering strong typing, easy testing, and built-in Validators.

  • FormGroup — groups related controls together
  • FormControl — a single input value with validation
  • FormArray — a dynamic list of controls (e.g., list of skills)
  • Validators — built-in: required, email, min, max, minLength, pattern

Code Example

// forms.component.ts
constructor(private fb: FormBuilder) {
  this.form = this.fb.group({
    name:  ['', [Validators.required, Validators.minLength(3)]],
    email: ['', [Validators.required, Validators.email]],
    skills: this.fb.array([
      this.fb.control('Angular', Validators.required)
    ])
  });
}

get skills(): FormArray {
  return this.form.get('skills') as FormArray;
}

addSkill() {
  this.skills.push(this.fb.control('', Validators.required));
}

onSubmit() {
  if (this.form.valid) {
    console.log(this.form.value);
  }
}

<!-- forms.component.html -->
<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <input formControlName="name" class="form-control">
  <div *ngIf="name.invalid && name.touched" class="error-msg">
    Name is required (min 3 chars)
  </div>

  <div formArrayName="skills">
    <div *ngFor="let skill of skills.controls; let i = index">
      <input [formControlName]="i" class="form-control">
      <button (click)="removeSkill(i)">Remove</button>
    </div>
    <button (click)="addSkill()">Add Skill</button>
  </div>

  <button type="submit" [disabled]="form.invalid">Submit</button>
</form>

Live Demo

Form status: INVALID