19

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?

3 Answers 3

62

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.

Sign up to request clarification or add additional context in comments.

7 Comments

great summary, I wonder if you might provide an example of what you feel a complex scenario might be?
Validation rules that change based on the user (different rules for different countries or admin vs standard user), adding input elements dynamically, waiting validation until after some amount of time that the user has stopped typing. Those are what comes immediately to mind. You can watch the course before you make up your mind: app.pluralsight.com/library/courses/angular-2-reactive-forms/…. You can sign up for a free week.
make sense to me!
Yes, that should be on this list @yurzui I didn't include it because this was part of a training course and I didn't have enough allocated time to properly explain the async vs sync difference and didn't want to just list it without explaining it. :-)
|
5

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.