What is the difference between Template-Driven and Reactive Forms?

What is the difference between Template-Driven and Reactive Forms?

What is the difference between Template-Driven and Reactive Forms?

Question

What is the difference between Template-Driven and Reactive Forms in Angular?

Answer

Template-Driven Forms

  • Form structure defined in the HTML template using ngModel
  • Angular infers the form model automatically
  • Simpler for basic forms, less boilerplate
  • Harder to test and work with dynamically
<!-- Requires FormsModule -->
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
  <input name="email" ngModel required email />
  <input name="password" ngModel required minlength="8" />
  <button [disabled]="f.invalid">Submit</button>
</form>

Reactive Forms

  • Form structure defined in the TypeScript class using FormBuilder
  • Explicit control over form state, validation, and value changes
  • Better for complex, dynamic forms
  • Easier to unit test
// Requires ReactiveFormsModule
form = this.fb.group({
  email:    ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(8)]],
});

// Programmatic access
this.form.get('email')?.setValue('[email protected]');
this.form.valueChanges.subscribe(values => console.log(values));

Comparison

Template-DrivenReactive
Form model locationTemplateComponent class
TestingDifficultEasy
Dynamic formsComplexEasy (FormArray)
ValidationDirectivesFunctions
Async validatorsPossible but messyClean API
All Comments