Validating user data with forms in Angular, which is essential for handling inputs,
validations, and data submission.
📝 Angular Forms: Two Approaches
Angular gives you two
powerful form systems:
Form
Type |
Description |
When
to Use |
Template-Driven |
Uses
HTML and Angular directives |
Simple
forms, quick setup |
Reactive
Forms |
Uses
code to define form structure |
Complex
forms, dynamic validation, better control |
✅ 1. Template-Driven Forms (Beginner-Friendly)
🔧
Setup:
Import FormsModule in
app.module.ts:
import { FormsModule
} from '@angular/forms';
@NgModule({
imports: [FormsModule],
})
export class AppModule {}
📋
Example:
app.component.html
<form
(ngSubmit)="onSubmit()" #userForm="ngForm">
<input name="name"
[(ngModel)]="user.name" required />
<input type="email"
name="email" [(ngModel)]="user.email" required />
<button type="submit"
[disabled]="userForm.invalid">Submit</button>
</form>
app.component.ts
export class
AppComponent {
user = { name: '', email: '' };
onSubmit() {
console.log('Form submitted:',
this.user);
}
}
✅ 2. Reactive Forms (More Powerful &
Scalable)
🔧
Setup:
Import
ReactiveFormsModule in app.module.ts:
import {
ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [ReactiveFormsModule],
})
export class AppModule {}
📋
Example:
user-form.component.ts
import { Component }
from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-user-form',
templateUrl:
'./user-form.component.html',
})
export class UserFormComponent {
userForm = new FormGroup({
name: new FormControl('',
[Validators.required]),
email: new FormControl('',
[Validators.required, Validators.email]),
});
onSubmit() {
if (this.userForm.valid) {
console.log('User:',
this.userForm.value);
}
}
}
user-form.component.html
<form
[formGroup]="userForm" (ngSubmit)="onSubmit()">
<input
formControlName="name" placeholder="Name" />
<div
*ngIf="userForm.get('name')?.invalid &&
userForm.get('name')?.touched">
Name is required
</div>
<input
formControlName="email" placeholder="Email" />
<div
*ngIf="userForm.get('email')?.invalid &&
userForm.get('email')?.touched">
Enter a valid email
</div>
<button
type="submit"
[disabled]="userForm.invalid">Submit</button>
</form>
✅ Bonus: Dynamic Fields, Custom Validators,
Async Validators
Reactive Forms really
shine when you need:
- Dynamic
form controls added at runtime
- Custom
validation logic
- Tracking
form status changes
- Integration
with services (like checking username availability)
🧠 Summary
Feature |
Template-Driven |
Reactive
Forms |
Setup |
FormsModule |
ReactiveFormsModule |
Syntax |
HTML-based |
Code-driven
(FormGroup) |
Validation |
Simple |
Powerful
+ custom |
Use
Case |
Quick,
simple forms |
Large,
dynamic, complex forms |
No comments:
Post a Comment