Angular, forms are used to collect user input, validate it, and handle submissions.
There are Two types of forms in Angular :
1)Template Driven Forms
2) Reactive Forms
1)Template Driven Forms
It is a traditional approach where DOM will create a form object and angular will inject the data into the form Object.
- Simpler and easier to use for small forms.
- Two-way data binding using [(ngModel)].
- Validation is added directly in the template using Angular directives.
2) Reactive Forms
The Form object will be programmatically created by angular and the entire FORM object will be synchronized with DOM.
- More complex
- uses FormControl and FormGroup for dynamic and robust forms.
Ex.html:
<div class="container mt-5">
<form>
Name:
<input type="text" name="name" [(ngModel)]="loginObj.name" placeholder="Enter a Name"><br>
Password:
<input type="text" [(ngModel)]="loginObj.password" name="password" #password="ngModel"
placeholder="Enter 4 digit Password" required minlength="3">
<div class="text-danger">
@if(password.touched && password.errors?.['required']){
<span>This is required</span>
}@else if(password.touched && password.errors?.['minlength']) {
<span>Min 3 char required</span>
}
</div>
<button class="btn btn-success" (click)="onSave()">Submit</button>
<button class="btn btn-danger" (click)="onReset()">Reset</button>
</form>
</div>
Data:{{formValue|json}}
Ex.ts:
export class TemplatedriComponent {
//imports: [FormsModule,CommonModule],
formValue:any;
loginObj:any={
name:'',
password:''
};
onSave(){
this.formValue = this.loginObj;
}
onReset(){
this.loginObj ={
name:'',
password:''
};
}}
Major Differences Between Template-Driven and Reactive Forms:
Feature | Template-Driven Forms | Reactive Forms |
---|---|---|
Form Model | Implicit, based on ngModel | Explicit, defined in the component class |
Validation | Declared in the template using directives like required, minlength | Declared in the component using Validators |
Form Control Access | Automatically managed by Angular | Manually created and managed using FormGroup, FormControl |
Two-Way Data Binding | Uses [(ngModel)] for two-way binding | No two-way binding, uses form control methods |
Dynamic Forms | Difficult to handle dynamically | Easier to handle dynamically by adding/removing controls |
Performance | Suitable for small forms | More suitable for large and complex forms |
Testability | More difficult to test due to logic in template | Easier to test since logic is in the component class |
Form State | Automatically managed by Angular | Explicitly managed in the component class |
Comments
Post a Comment