Skip to content
beginner Phase 7 · Reactive Forms and Validation

Building Forms with FormBuilder

Declare a typed form model in the component class.

40m
0 problems
Topic Progress 0%

Setting Up Reactive Forms

Reactive forms provide explicit, immutable form model management in the component class. They are the preferred approach for complex forms.

Importing ReactiveFormsModule

import { ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'app-login-form',
  imports: [ReactiveFormsModule],
  template: `...`,
})
export class LoginFormComponent {}

Creating a Form with FormBuilder

import { Component, inject } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/core';

@Component({
  selector: 'app-login-form',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
      <label>
        Email
        <input type="email" formControlName="email">
      </label>

      <label>
        Password
        <input type="password" formControlName="password">
      </label>

      <button type="submit" [disabled]="loginForm.invalid">Log in</button>
    </form>
  `,
})
export class LoginFormComponent {
  private fb = inject(FormBuilder);
  loginForm: FormGroup = this.fb.group({
    email: [''],
    password: [''],
  });

  onSubmit(): void {
    if (this.loginForm.valid) {
      console.log('Form value:', this.loginForm.value);
    }
  }
}

FormBuilder Methods

Method Purpose Example
group() Create a FormGroup this.fb.group({...})
control() Create a FormControl this.fb.control('')
array() Create a FormArray this.fb.array([])

FormControl with Validators

this.loginForm = this.fb.group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(8)]],
});

Accessing Form Values

// Get all values
const values = this.loginForm.value;
// { email: 'test@example.com', password: 'secret123' }

// Get a specific control
const emailControl = this.loginForm.get('email');
const emailValue = emailControl?.value;

// Check validity
const isValid = this.loginForm.valid;
const isDirty = this.loginForm.dirty;
const isTouched = this.loginForm.touched;

Reactive vs Template-Driven Forms

Angular offers two form approaches. Understanding the differences helps you choose the right one.

Reactive Forms

// Component class owns the form model
this.form = this.fb.group({
  email: ['', Validators.required],
});

// Template binds to the model
<input formControlName="email">

Template-Driven Forms

// Template owns the form model
// Component just declares fields
email = '';

// Template uses ngModel
<input [(ngModel)]="email" required>

Comparison

Feature Reactive Template-Driven
Model location Component class Template
Type safety Full Limited
Validation Component class Template directives
Dynamic fields Easy (FormArray) Difficult
Testing Easy (class-based) Hard (DOM-dependent)
Complex logic Clean separation Mixed concerns
Setup More boilerplate Minimal

When to Use Reactive Forms

  • Complex forms with dynamic fields
  • Forms with cross-field validation
  • Forms that need unit testing
  • Forms with complex business logic

When to Use Template-Driven Forms

  • Simple forms with 2-3 fields
  • Quick prototypes
  • Forms with minimal validation

Quiz

1. What module must be imported for reactive forms?

Question 1 options

2. What is the advantage of reactive forms over template-driven forms?

Question 2 options

3. How do you bind a template input to a reactive form control?

Question 3 options

Flashcards

Question

How do you create a reactive form?

Answer

Use FormBuilder.group() in the component class. Bind with [formGroup] and formControlName in the template.

Question

What is the advantage of reactive forms?

Answer

Type safety, testability, dynamic fields (FormArray), and clean separation of concerns.

Question

What module do reactive forms need?

Answer

ReactiveFormsModule from @angular/forms.

Revision Notes

Key Takeaways

  • 1. Reactive forms use FormBuilder.group() in the component class
  • 2. formControlName binds template inputs to form controls
  • 3. Reactive forms provide type safety and testability
  • 4. Prefer reactive forms for complex scenarios

Interview Tips

  • • Explain the difference between reactive and template-driven forms
  • • Be ready to describe when to use each approach
  • • Mention FormArray for dynamic fields

Cheat Sheet

Reactive Forms Basics Cheat Sheet

Setup:

import { ReactiveFormsModule } from '@angular/forms';

Create form:

this.form = this.fb.group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(8)]],
});

Template:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <input formControlName="email">
  <button type="submit" [disabled]="form.invalid">Submit</button>
</form>

Continue Learning