In angular 2 what is the difference between the template driven forms and reactive form. In which situations we need to use the template driven forms and reactive forms
Simply we can say
Reactive form can be used in the following situation
We can get entire form in a structured way by using "form.value"
If we have 4 fields First Name, Last Name, Email, Phone Number in reactive form.
HTML code will be
<form [formGroup]="form">
First Name <input formControlName="firstName">
Last Name <input formControlName="lastName">
Email <input formControlName="email">
Phone Number <input formControlName="phoneNumber">
</form>
We can get the values from the form like below
{
"firstName": "FName",
"lastName": "LName",
"email": "[email protected]",
"phoneNumber": "123"
}
by calling form.value, where form is FormGroup Variable that we created.
Template Driven Form : It can be used when using simple forms. Like login page. With the two way data binding. We can simply assign value to variable from ui and vice versa.
Simple example is if we are givng two way binding for the below input.
<input [(ngModel)]="username">
We can simply display the value that user is giving in the UI.
<p>Hello {{username}}!</p>