Forms are used to collect, validate, and submit user input in Angular applications.
Angular provides two approaches to handle forms:
-
Template-Driven Forms
-
Reactive Forms
Template-Driven vs Reactive Forms
| Feature | T emplate-Driven Forms | Reactive Forms |
|---|
| Form logic | In HTML template | In TypeScript |
| Data binding | Two-way (ngModel) | Explicit (FormControl) |
| Validation | Template-based | Code-based |
| Scalability | Small forms | Large/complex forms |
| Testing | Harder | Easier |
| Flexibility | Less | More |
🟢 Template-Driven Forms
✅ Characteristics
-
Logic written mostly in HTML
-
Uses
[(ngModel)] -
Easy to learn
-
Best for simple forms
📌 Required Module
import { FormsModule } from '@angular/forms';
📄 Example
HTML
<form #myForm="ngForm">
<input name="email" ngModel required email />
<button [disabled]="myForm.invalid">Submit</button>
</form>
✔ Validation
required
minlength
maxlength
email
pattern
How to intreact with Radio button, Checkbox, Listbox and Dropdownlist with example:
import { FormsModule } from '@angular/forms';
import { Component } from '@angular/core';
@Component({
selector: 'app-student',
templateUrl: './student.component.html'
})
export class StudentComponent {
// Model object (optional but recommended)
student = {
name: '',
gender: '',
isActive: false,
course: '',
skills: [] as string[]
};
/* onSubmit(form: any) {
console.log('Form Value:', form.value);
console.log('Student Object:', this.student);
}*/
result: string = '';
onSubmit(form: any) {
this.result =
`Name: ${this.student.name}, ` +
`Gender: ${this.student.gender}, ` +
`Active: ${this.student.isActive ? 'Yes' : 'No'}, ` +
`Course: ${this.student.course}, ` +
`Skills: ${this.student.skills.join(', ')}`;
}
}
Student.Component.html
<h2>Student Registration Form</h2>
<form #studentForm="ngForm" (ngSubmit)="onSubmit(studentForm)">
<!-- TEXTBOX -->
<label>Name:</label><br />
<input
type="text"
name="name"
[(ngModel)]="student.name"
required
/>
<br /><br />
<!-- RADIO BUTTON -->
<label>Gender:</label><br />
<input
type="radio"
name="gender"
value="Male"
[(ngModel)]="student.gender"
/> Male
<input
type="radio"
name="gender"
value="Female"
[(ngModel)]="student.gender"
/> Female
<br /><br />
<!-- CHECKBOX -->
<label>
<input
type="checkbox"
name="isActive"
[(ngModel)]="student.isActive"
/>
Active Student
</label>
<br /><br />
<!-- DROPDOWN LIST -->
<label>Course:</label><br />
<select
name="course"
[(ngModel)]="student.course"
required
>
<option value="">-- Select Course --</option>
<option value="Angular">Angular</option>
<option value="React">React</option>
<option value="Java">Java</option>
</select>
<br /><br />
<!-- LISTBOX (MULTI SELECT) -->
<label>Skills:</label><br />
<select
name="skills"
[(ngModel)]="student.skills"
multiple
size="4"
>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<option value="JavaScript">JavaScript</option>
<option value="Angular">Angular</option>
</select>
<br /><br />
<button type="submit" [disabled]="studentForm.invalid">
Submit
</button>
</form>
<hr />
<h3>Form Output</h3>
<pre>{{ student | json }}</pre>
Reactive Forms
✅ Characteristics
Form logic written in TypeScript
Uses FormGroup, FormControl
Highly scalable & testable
Best for enterprise applications
📌 Required Module
import { ReactiveFormsModule } from '@angular/forms'
Component (TS)
form = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
});
in .html file
<form [formGroup]="form">
<input formControlName="email" />
<button [disabled]="form.invalid">Submit</button>
</form>
✔ Advantages
Strong validation control
Dynamic forms
Better error handling
Clean separation of logic
Create Normal Addition Program in Angular Framework:
import { ReactiveFormsModule } from '@angular/forms';
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-addition',
templateUrl: './addition.component.html'
})
export class AdditionComponent {
addForm = new FormGroup({
num1: new FormControl('', Validators.required),
num2: new FormControl('', Validators.required)
});
result: number = 0;
calculate() {
const n1 = Number(this.addForm.value.num1);
const n2 = Number(this.addForm.value.num2);
this.result = n1 + n2;
}
}
Html File
<form [formGroup]="addForm" (ngSubmit)="calculate()">
<label>Number 1:</label>
<input type="number" formControlName="num1" />
<br /><br />
<label>Number 2:</label>
<input type="number" formControlName="num2" />
<br /><br />
<button type="submit" [disabled]="addForm.invalid">
Add
</button>
</form>
<h3>Result: {{ result }}</h3>
➕ Addition Program (Reactive Form) with Validationimport { ReactiveFormsModule } from '@angular/forms';
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-addition',
templateUrl: './addition.component.html'
})
export class AdditionComponent {
addForm = new FormGroup({
num1: new FormControl('', [
Validators.required,
Validators.pattern('^[0-9]+$')
]),
num2: new FormControl('', [
Validators.required,
Validators.pattern('^[0-9]+$')
])
});
result: number | null = null;
calculate() {
if (this.addForm.invalid) {
this.addForm.markAllAsTouched();
return;
}
const n1 = Number(this.addForm.value.num1);
const n2 = Number(this.addForm.value.num2);
this.result = n1 + n2;
}
}
<form [formGroup]="addForm" (ngSubmit)="calculate()">
<!-- NUMBER 1 -->
<label>Number 1:</label>
<input type="text" formControlName="num1" />
<div *ngIf="addForm.get('num1')?.touched && addForm.get('num1')?.errors">
<small *ngIf="addForm.get('num1')?.errors?.['required']">
Number 1 is required
</small>
<small *ngIf="addForm.get('num1')?.errors?.['pattern']">
Only numbers allowed
</small>
</div>
<br />
<!-- NUMBER 2 -->
<label>Number 2:</label>
<input type="text" formControlName="num2" />
<div *ngIf="addForm.get('num2')?.touched && addForm.get('num2')?.errors">
<small *ngIf="addForm.get('num2')?.errors?.['required']">
Number 2 is required
</small>
<small *ngIf="addForm.get('num2')?.errors?.['pattern']">
Only numbers allowed
</small>
</div>
<br />
<button type="submit" [disabled]="addForm.invalid">
Add
</button>
</form>
<h3 *ngIf="result !== null">Result: {{ result }}</h3>
0 Comments
POST Answer of Questions and ASK to Doubt