What are the differences between template driven forms and reactive forms in angular 2

Vijay Ramesh picture Vijay Ramesh · Jul 24, 2017 · Viewed 23.3k times · Source

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

Answer

vivekkurien picture vivekkurien · Jul 10, 2018

Simply we can say

Reactive form can be used in the following situation

  • Complex forms with more number of fields.
  • Multiple complex validation are there. Custom validations are required
  • Require JSON structure to be send with the values in the form.

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>