Template-Driven Forms in Angular
Template-Driven Forms in Angular provide a simple, declarative way to build forms using Angular directives in the HTML template. They're perfect for basic forms, quick prototypes, or when you want to avoid a lot of TypeScript code.
✅ Key Characteristics
- Defined in HTML using directives like
ngModel,ngForm,ngSubmit - Minimal TypeScript logic
- Powered by
FormsModule
📦 Prerequisite
Import FormsModule in your AppModule.
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [FormsModule]
})
export class AppModule { }
🧱 Basic Example
📄 Template (app.component.html)
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
<label>Name:
<input type="text" name="name" ngModel required />
</label>
<br />
<label>Email:
<input type="email" name="email" ngModel required />
</label>
<br />
<button type="submit" [disabled]="!userForm.valid">Submit</button>
</form>
🧠Component (app.component.ts)
export class AppComponent {
onSubmit(form: any) {
console.log('Form submitted!', form.value);
}
}
🛠️ Features
✅ Validation (HTML5 + Angular)
<input name="email" ngModel required email />
Use userForm.controls['email']?.valid in the template to check for errors.
✅ Accessing Form Controls
<input name="name" ngModel #nameCtrl="ngModel" required />
<div *ngIf="nameCtrl.invalid && nameCtrl.touched">
Name is required
</div>
📊 Template-Driven vs Reactive Forms
| Feature | Template-Driven | Reactive |
|---|---|---|
| Complexity | Low | Medium to High |
| Code Location | Mostly HTML | Mostly TypeScript |
| Suitable For | Simple forms | Complex & dynamic forms |
| Validation | Declarative in HTML | Programmatic in TypeScript |
Comments
Post a Comment