In HTML, forms are used to collect a data from the user and based on that he/she can do their respective operations. Mostly applications use forms for login, signup, or get an some sensitive information etc. In Angular, they provide two types of forms,
- Template Driven Forms
- Reactive Forms
Basically these two forms capture the inputs from the user, validate the user input and create a form model based upon the requirements. And also you can able to track the data from the view to the model.
Template Driven Forms
Most of the initial angular applications were using Template Driven Forms. They used to track the data between the view and the model using ng-model. Using ng-model you should be able to get the data from the view and you should be able to use it for further operations.
If you want to use template driven forms, you should import the FormsModule from @angular/forms
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [
AppComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
We have imported the FormsModule in app.module.ts such as now we are good to use template driven forms.
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app',
templateUrl: 'app.component.html'
})
export class AppComponent {
name: string;
age: string;
onSubmit(){
console.log(this.name);
console.log(this.age);
// will print the respective value from the text boxes
}
}
In the typescript file, we have two variables name and age. So we are going to use these two properties to bind the value from the view(HTML) using ng-model.
app.component.html
<form name="form"
(ngSubmit)="f.form.valid && onSubmit()" #
f="ngForm" novalidate>
<input type="text"
[(ngModel)]="name" /><br />
<input type="text"
[(ngModel)]="age" /><br />
<button type="button"
(click)="onSubmit()">Submit</button>
</form>
So in html, we have two text boxes and if they click the the submit button, the respective values which are entered by the user in the text boxes will print in the console.
Basically angular tracks us the three basic form states, using that you should be able to change the CSS or make some custom validation. They are,
- touched or Untouched
- valid or invalid
- pristine or dirty
Here is a link which demonstrates about the template driven form.
Stackblitz link => https://bit.ly/367zcEx
Reactive Forms(Model-Driven Forms)
Reactive forms are more powerful than template driven forms. And also there are lot of operations that can be easily done when compared to template driven forms since it uses Functional Programming. My opinion,
If you use more than two input box,
go for Reactive Forms
So if you want to use reactive forms in your application, you should import ReactiveFormsModule instead of FormsModule
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {ReactiveFormsModule} from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ BrowserModule,ReactiveFormsModule],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
And then you have to create FormBuilder/FormGroup which contains various FormControls or it may contain nested FormGroups. A FormControl can be a group or an array of FormControls.
app.component.ts
this.SignupForm = new FormGroup({
'userData': new FormGroup({
'username':new FormControl(null,[Validators.required,this.forbiddenNames.bind(this)]),
'email':new FormControl(null,[Validators.required,Validators.email],this.forbiddenEmails),
})
});
onSubmit(){
console.log(this.SignupForm
.get('userData').get('userName').value);
//will print the respective usernName value entered in the input box
}
So above we have an SignupForm which is a FormGroup and it has a nested FormGroup called userData under which we have various FormControls such as username and email.
app.component.html
<form [formGroup]="SignupForm" (ngSubmit)="onSubmit()">
<div formGroupName="userData">
<div class="form-group">
<label for="username">UserName</label>
<input type="text" class="form-control"
id="username" formControlName = "username">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control"
id="email" formControlName = "email">
</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
So on the above code we are binding the values using formControlName and here also it has the same three form states.
Basically both looks similar but there are various differences in using reactive form and template driven form.
Here is a link which demonstrates about the reactive form.
Stackblitz => https://bit.ly/36alrET
Reactive Forms vs Template Driven Forms
Form Validation
In reactive forms we have form validation that can be easily done using Validators. Basically it is function where you can do all sort of validations you want.
But in template driven forms, you should make use of directives for your validations which is tedious when compared to template driven form.
Usability
Reactive Forms are more flexible but needs a lot of practice to get more comfortable. And also it’s more robust and scalable.
Whereas template driven forms are easy to use but when your form gets bigger it’s not more flexible to use.
Data binding
There is no data binding in reactive forms. Basically the data are immutable.
We use Two way data binding in template driven forms.
Coding
When your form gets bigger, reactive form will not get complex and there will be only minimal html code and more component code.
But in template driven forms, your form looks nasty and there will be more html code and minimal component code.
Testing
Easier unit testing in reactive forms.
Unit testing is an another challenge in template driven forms.
Conclusion
As you can there are lot of debates going on in using the template driven and reactive forms. But I prefer reactive forms rather than template driven forms because you don’t know when your form gets bigger. For more complex scenarios, reactive form is the right choice.
And also the migration from template driven to reactive form is a bit complex, but it would be very useful in the future if you migrate your forms from template driven to reactive.
In our next blog we will explore about Angular directives.
Happy Coding!
Cheers! 🙂
Leave a Reply