Reactive Forms & FormBuilder

🅰️ Angular Lesson 10 Intermediate

Reactive forms build explicit form control models in your component class, providing robust validation, easier testing, and real-time reactive features.

1 FormGroup, FormControl and Validators

Unlike template-driven forms, reactive forms define the form model programmatically:

  • FormControl: Tracks the value and validation status of an individual form input.
  • FormGroup: Groups related FormControls into a single object, tracking their collective validity.
  • Validators: Static helper functions used to check input validity (e.g. Validators.required, Validators.email, Validators.pattern()).
  • FormBuilder: A helper service that simplifies the syntax of creating large form groups.
2 Reactive Form Implementation

Let's check how to construct a reactive form in TypeScript:

TypeScript — Reactive Form Setup
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html'
})
export class RegisterComponent implements OnInit {
  registerForm!: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.registerForm = this.fb.group({
      username: ['', [Validators.required, Validators.minLength(4)]],
      email: ['', [Validators.required, Validators.email]]
    });
  }

  onSubmit() {
    if (this.registerForm.valid) {
      console.log('Form Submitted Data:', this.registerForm.value);
    }
  }
}

Bind this form model to your HTML template using the formGroup and formControlName directives:

HTML — Reactive Form Template
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
  <input formControlName="username" placeholder="Username">
  <input formControlName="email" type="email" placeholder="Email">
  <button type="submit" [disabled]="registerForm.invalid">Register</button>
</form>
3 Code Challenge
Challenge: Write a custom validator function that checks if a user input does not contain the word "admin", and add it to the username input field.