Reactive Forms: FormArray for Dynamic Fields
Build dynamic forms where users can add or remove items, like multiple phone numbers or addresses.
FormArray is used when you have a list of form controls that can grow or shrink. Real examples: - multiple phone numbers - skills list - multiple shipping addresses ## Step 1: Build a FormArray ```ts import { Component } from '@angular/core'; import { ReactiveFormsModule, FormArray, FormControl, FormGroup, Validators } from '@angular/forms'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-skills-form', standalone: true, imports: [ReactiveFormsModule, CommonModule], templateUrl: './skills-form.component.html', }) export class SkillsFormComponent { form = new FormGroup({ name: new FormControl('', { nonNullable: true, validators: [Validators.required] }), skills: new FormArray<FormControl<string>>([ new FormControl('HTML', { nonNullable: true }), ]), }); get skills() { return this.form.controls.skills; } addSkill() { this.skills.push(new FormControl('', { nonNullable: true })); } removeSkill(index: number) { this.skills.removeAt(index); } submit() { console.log(this.form.value); } } ``` ## Step 2: Template ```html <form [formGroup]="form" (ngSubmit)="submit()"> <label>Name</label> <input formControlName="name" /> <h3>Skills</h3> <div formArrayName="skills"> <div *ngFor="let ctrl of skills.controls; let i = index"> <input [formControlName]="i" placeholder="Skill" /> <button type="button" (click)="removeSkill(i)">Remove</button> </div> </div> <button type="button" (click)="addSkill()">Add Skill</button> <button type="submit">Save</button> </form> ``` ## Why this is advanced and useful This pattern powers most “add more” experiences in professional apps. > Next: Async validators, checking email uniqueness from an API.