Thuta Learning
IntermediateWeb Developmentintermediate

Reactive Forms

Relax. We'll talk through this in plain words — no textbook voice.

Reactive Forms build forms programmatically using TypeScript code. They're the best choice for complex forms.

⚠️ Important: ReactiveFormsModule needs to be imported.

typescript
// app.module.ts
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [ReactiveFormsModule]
})

// component.ts
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class MyComponent implements OnInit {
  userForm: FormGroup;
  
  constructor(private fb: FormBuilder) {}
  
  ngOnInit() {
    this.userForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.email]],
      age: ['', [Validators.required, Validators.min(18)]]
    });
  }
  
  onSubmit() {
    if (this.userForm.valid) {
      console.log(this.userForm.value);
    }
  }
}

// component.html
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  <input formControlName="name" placeholder="Name">
  <input formControlName="email" placeholder="Email">
  <input formControlName="age" type="number" placeholder="Age">
  <button [disabled]="!userForm.valid">Submit</button>
</form>
You should see
(The form can be controlled entirely from TypeScript, making it easy to add complex validations)
Reactive Forms | Thuta Learning