What is the difference between Template-Driven and Reactive Forms in Angular?
ngModel<!-- 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>
// 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));
| Template-Driven | Reactive | |
|---|---|---|
| Form model location | Template | Component class |
| Testing | Difficult | Easy |
| Dynamic forms | Complex | Easy (FormArray) |
| Validation | Directives | Functions |
| Async validators | Possible but messy | Clean API |
All Comments