Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Reactive Forms vs Template Forms

We are starting a new Angular 2 project and are considering whether to use Reactive Forms or Template Forms. Background reading here: https://angular.io/guide/reactive-forms

As far as I can tell, the biggest advantage of Reactive Forms is that they're synchronous, but we have simple forms and I don't think asynchronicity will cause us issues. There seems to be much more overhead with Reactive, on the surface more code to do the same things.

Can someone provide a solid use case where I would use Reactive over the simpler Template Forms?

like image 253
bwobbones Avatar asked Jun 15 '17 02:06

bwobbones


People also ask

What is the difference between template and Reactive forms?

Reactive forms are mostly synchronous in nature whereas, Template driven forms are asynchronous. Logic Driven Source: The template-driven approach draws logic from the template, whereas in reactive driven forms the logic resides mainly in the component or typescript code.

What is the difference in how Reactive forms and template driven forms validate the information a user enters?

Template-driven forms are asynchronous in nature, whereas Reactive forms are mostly synchronous. In a template-driven approach, most of the logic is driven from the template, whereas in reactive-driven approach, the logic resides mainly in the component or typescript code.

Why is Reactive form better?

As the validation logic gets declared in the component class, unit tests are easily written for the logic to ensure the code is bug-free. Reactive forms take away the complexity of writing custom validators. They allow you to define custom validator functions and bind them to the form during declaration.

What is the difference between reactive and template driven forms in angular?

Both reactive and template driven forms provide efficient ways for building forms in Angular. While the template driven syntax offers a more familiar approach, reactive forms offer a more dynamic way of building form groups and controls. Your thoughts?

What are @angular 2 forms?

Angular 2 offers developers two technologies for building forms: template-driven forms and reactive forms. Both technologies are part of the @angular/forms library and contain the same set of form control classes.

What is the difference between formcontrol and formgroup in angular?

Both the above approaches of angular forms have few common building blocks holding the following attributes, FormControl is used mainly for monitoring user input and authentication of the individual form control. FormGroup used to track the same values and authentication status for a collection of a form of control.

What is form validation in angular reactive form?

In angular reactive form module, the component class is the main source of truth, therefore the validation functions are included in the form control model of the component class. In this way, angular can call these validators anytime there is a change in the value of the form control.


3 Answers

Template-driven vs Reactive Forms

This is a slide from my course on Forms in Pluralsight. Some of these points may be arguable, but I worked with the person from the Angular team that developed Forms to put together this list.

like image 78
DeborahK Avatar answered Oct 23 '22 02:10

DeborahK


The advantage of template driven design is its simplicity. There will be not much code in the controller. Most logic happens in the template. This is suitable for simple forms which do not need much logic behind the html-code.

But each form has a state that can be updated by many different interactions and it's up to the application developer to manage that state and prevent it from getting corrupted. This can get hard to do for very large forms and can introduce bugs.

On the other hand, if more logic is needed, there is often also a need for testing. Then the reactive model driven design offers more. We can unit-test the form validation logic. We can do that by instantiating the class, setting some values in the form controls and perform tests. For complex software this is absolutely needed for design and maintainability. The disadvantage of reactive model driven design is its complexity.

There is also a way of mixing both design-types, but that would be having the disadvantages of both types.

You can find this explained with simple example code for both ways here: Introduction to Angular Forms - Template Driven vs Model Driven or Reactive Forms

like image 21
Bert Verhees Avatar answered Oct 23 '22 02:10

Bert Verhees


behind the scene they are same. In reactive form, this is what u import in app.module.ts:

import { ReactiveFormsModule } from '@angular/forms';

imports: [BrowserModule, ReactiveFormsModule],

then in your parent.component.ts

import { FormGroup, FormControl, Validators } from '@angular/forms';

cardForm = new FormGroup({
name: new FormControl('', [
  Validators.required,
  Validators.minLength(3),
  Validators.maxLength(5),
]), 

});

cardForm is an instance of FormGroup. We need to connect it to the form itself.

<form [formGroup]="cardForm" (ngSubmit)="onSubmit()"></form>

This tells that this form will be handled by "cardForm". inside each input element of the form, we will add controller to listen for all the changes and pass those changes to the "cardForm".

<form [formGroup]="cardForm" (ngSubmit)="onSubmit()">
      <app-input label="Name" [control]="cardForm.get('name')"> </app-input>
 </form>


 cardForm.get('name')=  new FormControl('initValue', [
                           Validators.required,
                           Validators.minLength(3),
                           Validators.maxLength(5),
                           ]), 

in a nutshell, FormControl instances are placed in the input elements, they listen for all change and report them to FormGroup instance. We are setting up FormGroup and FormControl in the class component explciitly.

if you work with template forms, you do not set up anything in the parent.component.ts. you write your code inside the parent.component.html. BUT at this moment, angular behind the scene will still create FormGroup and will handle the form through FormGroup. in app.module.ts

  import { FormsModule } from '@angular/forms';

  imports: [BrowserModule, FormsModule],

we are not writing any code for the FormGroup and FormControl. we go to the template file:

 <form (ngSubmit)="onSubmit()" #emailForm="ngForm">

#emailForm creates a ref to the "FormGroup" that created behind the scene. with this we can access to all of the properties of FormGroup like "touched", "valid" etc.

then we place input element inside the form:

  <input
    type="email"
    required
    name="email"
    [(ngModel)]="email"
    #emailControl="ngModel"
  />
  • ngModel is directive. tells Angular, we want to keep track of the value in this input. It will attach alot of event handler to the input element.

  • [(ngModel)] is two way binding. property binding and event handling syntax put together. if the value "email" in the class changes, update the input value, likewise if the input value changes, update the "email" in the class. we already defined "email" in the class component

        export class AppComponent {
        email: string; // [(ngModel)] communicates with this
        onSubmit() {
        console.log(this.email);
      }
     } 
    
  • #emailControl is the reference to the input control. name could be anything.

    emailControl===emailForm.controls.email
    

So in this template form, #emailForm represents the FormGroup, #emailControl represents the FormControl.

  • in reactive forms, we write our validation logic inside the FormControl explicitly. But with template, if you check the input element we added "required". when angular sees this, it will automatically assign it to Validator.required
like image 2
Yilmaz Avatar answered Oct 23 '22 02:10

Yilmaz