Angular Forms: Reactive vs Template-Driven #2
Understanding Reactive vs Template-Driven Forms is very important in Angular interviews, especially for form-heavy apps like admin dashboards or CRMs.
Letโs break this down in pen-and-paper-friendly style so you can write notes easily and revise quickly.
Angular offers two approaches to build forms:
| Type | Controlled From |
|---|---|
| Template-Driven | Template (HTML) |
| Reactive | Component (TS) |
๐งฉ 1. Template-Driven Forms
- Easy to write
- Uses Angular directives (
ngModel,required, etc.) - Best for simple forms
โ Key Features:
- 2-way binding with
[(ngModel)] - Uses
FormsModule - Validations done via HTML attributes
๐ Example:
HTML (template-driven):
<form #formRef="ngForm" (ngSubmit)="submitForm(formRef)">
<input type="text" name="username" [(ngModel)]="user.name" required />
<button type="submit">Submit</button>
</form>
TS:
user = { name: '' };
submitForm(form: NgForm) {
console.log(form.value); // Access all form data
}
๐ง 2. Reactive Forms
- More powerful & scalable
- Form is created and managed in TypeScript
- Best for complex, dynamic forms
โ Key Features:
- Uses
FormControl,FormGroup,FormBuilder - Needs
ReactiveFormsModule - All logic lives in component
๐ Example:
TS:
form: FormGroup;
ngOnInit() {
this.form = this.fb.group({
username: ['', Validators.required]
});
}
submitForm() {
console.log(this.form.value);
}
HTML:
<form [formGroup]="form" (ngSubmit)="submitForm()">
<input type="text" formControlName="username" />
<button type="submit">Submit</button>
</form>
โ๏ธ Comparison Table
| Feature | Template-Driven | Reactive |
|---|---|---|
| Code Location | Mostly in HTML | Mostly in TS |
| Setup | Easy | More setup |
| Validation | HTML attributes | TypeScript (validators) |
| Best For | Simple forms | Complex/dynamic forms |
| Data Flow | Two-way binding | Unidirectional |
| Testing | Harder | Easier (more predictable) |
| Modules Needed | FormsModule |
ReactiveFormsModule |
๐ก Interview Tips
- Use template-driven for simple contact/login forms
- Use reactive for forms with:
- Dynamic fields (like Add/Remove rows)
- Conditional validations
- Complex interactions
๐ฏ Common Interview Questions
- Which form type is better for dynamic validations?
๐ Reactive Forms - Whatโs the difference between FormControl & ngModel?
๐FormControlis for reactive forms (TS driven),ngModelis for template-driven (HTML driven) - Can we mix both?
๐ Technically yes, but Angular recommends not to mix.
Would you like to go deeper into:
FormArrayin Reactive Forms (used in tables or dynamic inputs)?- Or learn built-in validation + custom validators next?
Just say the word โ Iโll prep it in your note-friendly format! ๐๐๏ธ