Categories: AngularJSWeb

Angular – Reactive or Template-driven Forms?

This article represents quick introduction to two different kind of forms which can be created in Angular 2 or Angular 4. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.

Following are the key points discussed later in this article:

  • Template-driven forms
  • Reactive forms

Template-driven forms

Template-driven forms are the most trivial type of form that can be quickly created in Angular 2. Following are key aspects of creating template-driven form.

  • These forms are asynchronous in nature.
  • These forms require inclusion/import of FormsModule in the root module, AppModule which is placed in the root folder of the app. Following is the sample code:
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { AppComponent } from './app.component';
    import { LoginComponent } from './login/login.component';
    
    @NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent, LoginComponent ],
    bootstrap: [ AppComponent ]
    })
    export class AppModule { }
    
  • In the form, ngModel is used for two-way data binding. Take a look at sample code given below.
      <input type="email"
             class="form-control"
             id="email"
             placeholder="Email"
             required
             [(ngModel)]="model.email"
             name="email"
      >
    
  • Validation related login is placed into the UI code. Take a look at following example where email field validation logic is placed just beside input element.
      <input type="text"
             class="form-control"
             id="fullname"
             placeholder="Full Name"
             required
             [(ngModel)]="model.fullname"
             name="fullname"
             #fullname="ngModel"
      >
      <div [hidden]="fullname.valid || fullname.pristine"
        class="alert alert-danger">
        Full name is required
      </div>
    

Reactive Forms

Reactive forms are based on reactive style of programming. Following are key aspects of reactive forms:

  • These forms are synchronous in nature unlike template-driven forms.
  • These forms require inclusion/import of ReactiveFormsModule in the root module, AppModule which is placed in the root folder of the app. Following is the sample code:
    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { ReactiveFormsModule }   from '@angular/forms';
    
    import { AppComponent }  from './app.component';
    import { LoginComponent } from './rlogin/login.component';
    
    @NgModule({
      imports:      [ BrowserModule, ReactiveFormsModule ],
      declarations: [ AppComponent, LoginComponent ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    
  • Form controls are created and managed in component code rather than the UI unlike the template-driven forms.
  • Validation logic is placed within Component rather than the UI code as like template driven forms. Take a look at sample code given below which resides in the Component class.
    </pre>
    export class LoginComponent {
    
    formErrors = {
        'email': '',
        'password': ''
      };
    
    validationMessages = {
        'email': {
          'required': 'Email is required.'
        },
        'password': {
          'required': 'Password is required.'
        }
      };
    
    createForm() {
      this.loginForm.valueChanges
       .subscribe(data => this.onValueChanged(data));
    
      this.onValueChanged();
     }
    
     onValueChanged(data?: any) {
       if (!this.loginForm) {
        return;
       }
       const form = this.loginForm;
    
       for (const field in this.formErrors) {
        this.formErrors[field] = '';
        const control = form.get(field);
    
        if (control && control.dirty && !control.valid) {
         const messages = this.validationMessages[field];
         for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
         }
        }
       }
     }
    
  • Logic related with communicating with server is delegated to services.
  • Following are key Form-related classes which are used to manage Form UI elements:
    • AbstractControl: AbstractControl represents base class from which below mentioned classes are derived.
    • FormControl: Instances of FormControl represents actual UI element.
      email = new FormControl('', Validators.required);
      
    • FormGroup: These are used to group one or more AnstractControl interfaces. Following represents a sample login form.
      loginForm = new FormGroup({
      email: new FormControl('', Validators.required)
      });
      
    • FormArray: These are used to hold AbstractConrol interfaces in an array.

 

Latest posts by Ajitesh Kumar (see all)
Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

View Comments

Share
Published by
Ajitesh Kumar

Recent Posts

What are AI Agents? How do they work?

Artificial Intelligence (AI) agents have started becoming an integral part of our lives. Imagine asking…

2 weeks ago

Agentic AI Design Patterns Examples

In the ever-evolving landscape of agentic AI workflows and applications, understanding and leveraging design patterns…

2 weeks ago

List of Agentic AI Resources, Papers, Courses

In this blog, I aim to provide a comprehensive list of valuable resources for learning…

2 weeks ago

Understanding FAR, FRR, and EER in Auth Systems

Have you ever wondered how systems determine whether to grant or deny access, and how…

3 weeks ago

Top 10 Gartner Technology Trends for 2025

What revolutionary technologies and industries will define the future of business in 2025? As we…

3 weeks ago

OpenAI GPT Models in 2024: What’s in it for Data Scientists

For data scientists and machine learning researchers, 2024 has been a landmark year in AI…

3 weeks ago