Front-End Web Development

Exploring Forms in Angular – types, benefits and differences   

10 min read

While developing a web application, or setting dynamic pages and meta tags we need to deal with multiple input elements and value types, such limitations could seriously hinder our work – in terms of either data flow control, data validation, or user experience.  

This article is an excerpt from the book, ASP.NET Core 5 and Angular, Fourth Edition by Valerio De Sanctis – A revised edition of a bestseller that includes coverage of the Angular routing module, expanded discussion on the Angular CLI, and detailed instructions for deploying apps on Azure, as well as both Windows and Linux. 

Sure, we could easily work around most of the issues by implementing some custom methods within our form-based components; we could throw some errors such as isValid(), isNumber(), and so on here and there, and then hook them up to our template syntax and show/hide the validation messages with the help of structural directives such as *ngIf, *ngFor, and the like. However, it would be a horrible way to address our problem; we didn’t choose a feature-rich client-side framework such as Angular to work that way. 

Luckily enough, we have no reason to do that since Angular provides us with a couple of alternative strategies to deal with these common form-related scenarios: 

  • Template-Driven Forms
  • Model-Driven Forms, also known as Reactive Forms

Both are highly coupled with the framework and thus extremely viable; they both belong to the @angular/forms library and share a common set of form control classes. However, they also have their own specific sets of features, along with their pros and cons, which could ultimately lead to us choosing one of them. 

Let’s try to quickly summarize these differences. 

Template-Driven Forms

If you’ve come from AngularJS, there’s a high chance that the Template-Driven approach will ring a bell or two. As the name implies, Template-Driven Forms host most of the logic in the template code; working with a Template-Driven Form means: 

  • Building the form in the .html template file
  • Binding data to the various input fields using ngModel instance
  • Using a dedicated ngForm object related to the whole form and containing all the inputs, with each being accessible through their name.

These things need to be done to perform the required validity checks.To understand this, here’s what a Template-Driven Form looks like: 

<form novalidate autocomplete="off" #form="ngForm"
(ngSubmit)="onSubmit(form)"> 

    <input type="text" name="name" value="" required 
        placeholder="Insert the city name..."  
        [(ngModel)]="city.Name" #title="ngModel" 
        /> 

    <span *ngIf="(name.touched || name.dirty) &&  
     name.errors?.required"> 
        Name is a required field: please enter a valid city name. 
    </span> 

    <button type="submit" name="btnSubmit"  
        [disabled]="form.invalid"> 
        Submit 
    </button>
 
</form> 

Here, we can access any element, including the form itself, with some convenient aliases – the attributes with the # sign – and check for their current states to create our own validation workflow.  

These states are provided by the framework and will change in real-time, depending on various things: touched, for example, becomes True when the control has been visited at least once; dirty, which is the opposite of pristine, means that the control value has changed, and so on. We used both touched and dirty in the preceding example because we want our validation message to only be shown if the user moves their focus to the <input name=”name”> and then goes away, leaving it blank by either deleting its value or not setting it. 

These are Template-Driven Forms in a nutshell; now that we’ve had an overall look at them, let’s try to summarize the pros and cons of this approach. Here are the main advantages of Template-Driven Forms:

  • Template-Driven Forms are very easy to write. We can recycle most of our HTML knowledge (assuming that we have any). On top of that, if we come from AngularJS, we already know how well we can make them work once we’ve mastered the technique.
  • They are rather easy to read and understand, at least from an HTML point of view; we have a plain, understandable HTML structure containing all the input fields and validators, one after another. Each element will have a name, a two-way binding with the underlying ngModel, and (possibly) Template-Driven logic built upon aliases that have been hooked to other elements that we can also see, or to the form itself.

Here are their weaknesses: 

  • Template-Driven Forms require a lot of HTML code, which can be rather difficult to maintain and is generally more error-prone than pure TypeScript.
  • For the same reason, these forms cannot be unit tested. We have no way to test their validators or to ensure that the logic we implemented will work, other than running an end-to-end test with our browser, which is hardly ideal for complex forms.
  • Their readability will quickly drop as we add more and more validators and input tags. Keeping all their logic within the template might be fine for small forms, but it does not scale well when dealing with complex data items.

Ultimately, we can say that Template-Driven Forms might be the way to go when we need to build small forms with simple data validation rules, where we can benefit more from their simplicity. On top of that, they are quite like the typical HTML code we’re already used to (assuming that we do have a plain HTML development background); we just need to learn how to decorate the standard <form> and <input> elements with aliases and throw in some validators handled by structural directives such as the ones we’ve already seen, and we’ll be set in (almost) no time. 

For additional information on Template-Driven Forms, we highly recommend that you read the official Angular documentation at: https://angular.io/guide/forms 

That being said; the lack of unit testing, the HTML code bloat that they will eventually produce, and the scaling difficulties will eventually lead us toward an alternative approach for any non-trivial form.

Model-Driven/Reactive Forms

The Model-Driven approach was specifically added in Angular 2+ to address the known limitations of Template-Driven Forms. The forms that are implemented with this alternative method are known as Model-Driven Forms or Reactive Forms, which are the exact same thing. 

The main difference here is that (almost) nothing happens in the template, which acts as a mere reference to a more complex TypeScript object that gets defined, instantiated, and configured programmatically within the component class: the form model. 

To understand the overall concept, let’s try to rewrite the previous form in a Model-Driven/Reactive way (the relevant parts are highlighted). The outcome of doing this is as follows:

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

     <input formControlName="name" required />   

     <span *ngIf="(form.get('name').touched || form.get('name').dirty)           
         && form.get('name').errors?.required">          
         Name is a required field: please enter a valid city name.   
     </span>  
 
     <button type="submit" name="btnSubmit"          
         [disabled]="form.invalid">   
           Submit   
     </button>  
 
</form> 

As we can see, the amount of required code is much lower. Here’s the underlying form model that we will define in the component class file (the relevant parts are highlighted in the following code): 

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

class ModelFormComponent implements OnInit { 
form: FormGroup;  
   ngOnInit() { 
    this.form = new FormGroup({ 
       title: new FormControl() 
    }); 
  } 
} 

Let’s try to understand what’s happening here: 

  • The form property is an instance of FormGroup and represents the form itself.
  • FormGroup, as the name suggests, is a container of form controls sharing the same purpose. As we can see, the form itself acts as a FormGroup, which means that we can nest FormGroup objects inside other FormGroup objects (we didn’t do that in our sample, though).
  • Each data input element in the form template – in the preceding code, name – is represented by an instance of FormControl.
  • Each FormControl instance encapsulates the related control’s current state, such as valid, invalid, touched, and dirty, including its actual value.
  • Each FormGroup instance encapsulates the state of each child control, meaning that it will only be valid if/when all its children are also valid.

Also, note that we have no way of accessing the FormControls directly like we were doing in Template-Driven Forms; we have to retrieve them using the .get() method of the main FormGroup, which is the form itself. 

At first glance, the Model-Driven template doesn’t seem too different from the Template-Driven one; we still have a <form> element, an <input> element hooked to a <span> validator, and a submit button; on top of that, checking the state of the input elements takes a bigger amount of source code since they have no aliases we can use. What’s the real deal, then? 

To help us visualize the difference, let’s look at the following diagrams: here’s a schema depicting how Template-Driven Forms work: 

Fig 1: Template-Driven Forms schematic

By looking at the arrows, we can easily see that, in Template-DrivenForms, everything happens in the template; the HTML form elements are directly bound to the DataModel component represented by a property filled with an asynchronous HTML request to the Web Server, much like we did with our cities and country table.  

That DataModel will be updated as soon as the user changes something, that is, unless a validator prevents them from doing that. If we think about it, we can easily understand how there isn’t a single part of the whole workflow that happens to be under our control; Angular handles everything by itself using the information in the data bindings defined within our template.  

This is what Template-Driven actually means: the template is calling the shots. Now, let’s take a look at the Model-Driven Forms (or Reactive Forms) approach: 

Fig 2: Model-Driven/Reactive Forms schematic

As we can see, the arrows depicting the Model-Driven Forms workflow tell a whole different story. They show how the data flows between the DataModel component – which we get from the Web Server – and a UI-oriented form model that retains the states and the values of the HTML form (and its children input elements) that are presented to the user. This means that we’ll be able to get in-between the data and the form control objects and perform a number of tasks firsthand: push and pull data, detect and react to user changes, implement our own validation logic, perform unit tests, and so on.

Instead of being superseded by a template that’s not under our control, we can track and influence the workflow programmatically, since the form model that calls the shots is also a TypeScript class; that’s what Model-Driven Forms are about. This also explains why they are also called Reactive Forms – an explicit reference to the Reactive programming style that favors explicit data handling and change management throughout the workflow. 

Summary  

In this article, we focused on the Angular framework and the two form design models it offers: the Template-Driven approach, mostly inherited from AngularJS, and the Model-Driven or Reactive alternative. We took some valuable time to analyze the pros and cons provided by both, and then we made a detailed comparison of the underlying logic and workflow. At the end of the day, we chose the Reactive way, as it gives the developer more control and enforces a more consistent separation of duties between the Data Model and the Form Model. 

About the author 

Valerio De Sanctis is skilled IT professional with 20 years of experience in lead programming, web-based development, and project management using ASP.NET, PHP, Java, and JavaScript-based frameworks. He held senior positions at a range of financial and insurance companies, most recently serving as Chief Technology and Security Officer at a leading IT service provider for top-tier insurance groups. He is an active member of the Stack Exchange Network, providing advice and tips on the Stack Overflow, ServerFault, and SuperUser communities; he is also a Microsoft Most Valuable Professional (MVP) for Developer Technologies. He’s the founder and owner of Ryadel and the author of many best-selling books on back-end and front-end web development. 

 

 

 
Expert Network

Expert Insight presents a new line of books from Packt Publishing that will sit alongside and complement the wider publishing program. We started publishing titles in this line in late 2017, and are adding new titles every month. The books of Expert Insight feature leading authors in their respective fields, who have significant experience and a profound knowledge of trending topics. We aim to provide a platform for expert insight and opinions, both from individual authors and from groups of experts working in the same field. Our titles are very much focused around the voice and identity of the author themselves and the opportunity for the reader to connect with the individual, supported by the author’s image on our covers.

Share
Published by
Expert Network

Recent Posts

Top life hacks for prepping for your IT certification exam

I remember deciding to pursue my first IT certification, the CompTIA A+. I had signed…

2 years ago

Learn Transformers for Natural Language Processing with Denis Rothman

Key takeaways The transformer architecture has proved to be revolutionary in outperforming the classical RNN…

3 years ago

Learning Essential Linux Commands for Navigating the Shell Effectively

Once we learn how to deploy an Ubuntu server, how to manage users, and how…

3 years ago

Clean Coding in Python with Mariano Anaya

Key-takeaways:   Clean code isn’t just a nice thing to have or a luxury in software projects; it's a necessity. If we…

3 years ago

Gain Practical Expertise with the Latest Edition of Software Architecture with C# 9 and .NET 5

Software architecture is one of the most discussed topics in the software industry today, and…

3 years ago

Understanding the Foundation of Protocol-oriented Design

When Apple announced Swift 2 at the World Wide Developers Conference (WWDC) in 2016, they…

3 years ago