Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
In Angular there are two approaches to creating forms:
| Characteristic | Template-driven Forms | Reactive Forms |
|---|---|---|
| Foundation | HTML template | TypeScript code |
| Module | FormsModule | ReactiveFormsModule |
| Management | Declarative (via template) | Imperative (via code) |
| Approach | Light, declarative | Flexible, programmatic |
| Validation | Via HTML attributes + directives | Via API and methods |
| Testing | More complex | Easier |
| Suitable for | Simple forms | Complex/dynamic forms |
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
<input name="username" ngModel required />
<input name="email" ngModel email />
<button type="submit">Submit</button>
</form>
onSubmit(form: NgForm) {
console.log(form.value);
}
ngModel for data binding.required, email) for validation.import { FormGroup, FormControl, Validators } from '@angular/forms';
form = new FormGroup({
username: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email])
});
onSubmit() {
console.log(this.form.value);
}
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input formControlName="username" />
<input formControlName="email" />
<button type="submit">Submit</button>
</form>
| Scenario | Recommended approach |
|---|---|
| Simple login form | Template-driven |
| Complex dynamic form with logic and validation | Reactive |
| Need for scaling and testing | Reactive |
| Quick and simple form implementation | Template-driven |
Important:
Both approaches can be combined, but better choose one and stick with it throughout project for consistency.