Back to course

RF: Using FormGroup and FormArray

The Complete Angular Developer: From Zero to Hero

46. RF: Using FormGroup and FormArray

Real-world forms require grouping controls. FormGroup and FormArray are containers that aggregate multiple FormControl instances.

1. FormGroup (Grouping Controls)

FormGroup tracks the value and validation status of a collection of FormControl instances. The form's overall value is a collection of key-value pairs.

Component Class Setup

We use the FormBuilder service (injectable) to simplify creating nested structures.

typescript import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class ProfileFormComponent { profileForm: FormGroup;

constructor(private fb: FormBuilder) { this.profileForm = this.fb.group({ firstName: ['', Validators.required], lastName: [''], address: this.fb.group({ // Nested FormGroup street: [''], city: ['', Validators.required] }) }); } }

Template Linking

We link the component's FormGroup to the <form> element using [formGroup] and then map controls using formControlName.

html

<button type="submit" [disabled]="profileForm.invalid">Save

2. FormArray (Dynamic Lists)

FormArray manages a collection of controls (or groups) where the number of controls is variable (e.g., list of phone numbers, dynamic skills list).

typescript this.profileForm = this.fb.group({ // ... other controls skills: this.fb.array([this.fb.control('Angular')]) });

// Method to add a new control dynamically addSkill() { (this.profileForm.get('skills') as FormArray).push(this.fb.control('')); }

// Template to display skills //

// <input *ngFor="let ctrl of skills.controls; let i=index" [formControlName]="i"> //