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
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": "test@123.com",
"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>
A comprehensive answer to a similar question can be found here: What are the practical differences between template-driven and reactive forms?
here is what Aravind is posted which is abstract and direct to the point. so I copy and paste the entire comparison:
Template Driven Forms Features
Reactive Forms Features
More flexible, but needs a lot of practice
Handles any complex scenarios
No data binding is done (immutable data model preferred by most developers)
More component code and less HTML markup
Reactive transformations can be made possible such as
Handling a event based on a debounce time
Handling events when the components are distinct until changed
Adding elements dynamically
A side by side pros and cons