Skip to content
Angular

Reactive Forms

Build a typed reactive form with FormBuilder and validators.

By EZ4Code Team
formsreactive-forms

Code

import { Component, inject } from "@angular/core";
import { FormBuilder, ReactiveFormsModule, Validators } from "@angular/forms";

@Component({
  selector: "app-login",
  standalone: true,
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="submit()">
      <input formControlName="email" placeholder="Email" />
      <input formControlName="password" type="password" />
      <button [disabled]="form.invalid">Login</button>
    </form>
  `
})
export class LoginComponent {
  private fb = inject(FormBuilder);
  form = this.fb.group({
    email: ["", [Validators.required, Validators.email]],
    password: ["", [Validators.required, Validators.minLength(6)]]
  });
  submit() {
    if (this.form.valid) console.log(this.form.value);
  }
}

Explanation

Reactive forms model form state as an immutable FormGroup of FormControls. FormBuilder reduces boilerplate, and Validators attach sync rules. The [formGroup] binding connects the model to the template, exposing validity and value streams.

More Angular Snippets