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
Below are some of the high-level differences between the two types: Template-driven forms make use of the "FormsModule", while reactive forms are based on "ReactiveFormsModule". Template-driven forms are asynchronous in nature, whereas Reactive forms are mostly synchronous.
[formControl] assigns a reference to the FormControl instance you created to the FormControlDirective . formControlName assigns a string for the forms module to look up the control by name.
Angular provides two different approaches to handling user input through forms: reactive and template-driven.
Template-driven forms use two-way data binding to update the data model in the component as changes are made in the template and vice versa. Angular supports two design approaches for interactive 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>
With the template driven approach you basically apply directives, such as ngModel, in your template. Based on these directives Angular will create formcontrol objects. This approach is good for building simple forms with basic validation (required, minlength, maxlength,...).
With the reactive approach you basically need to create new instances of the formcontrols and formcontrolgroups in your component. Reactive forms are also the best choice for building more complex forms and are better in case you have the intention to implement unit testing for your forms.
Checkout the following topic...
http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/
Angular2 Forms API, Template driven or Reactive?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With