What Are Angular Forms and How to Implement Them?

Forms are an integral part of a web application. Practically every application comes with forms to be filled in by the users. Angular forms are used to log in, update a profile, enter sensitive information, and perform many other data-entry tasks. In this article, you will learn about how to create a form and validate the information filled. Here’s the list of topics that will be covered: 

  • Types of Angular Forms
    • Template-Driven Approach
    • Reactive Approach
  • Form Control¬†
  • Form Group¬†
  • Demo
    • Form Creation
    • Adding Angular Form controls
    • Getting the JavaScript Object Representation
    • Form Validation

Types of Angular Forms

There are two types of form building supported by Angular Forms. 

  • Template-Driven Approach¬†
  • Reactive Approach¬†

Template-Driven Approach

  • In this method, the conventional form tag is used to create forms. Angular automatically interprets and creates a form object representation for the tag.¬†
  • Controls can be added to the form using the NGModel tag. Multiple controls can be grouped using the NGControlGroup module.¬†
  • A form value can be generated using the ‚Äúform.value‚ÄĚ object. Form data is exported as JSON values when the submit method is called.¬†
  • Basic HTML validations can be used to validate the form fields. In the case of custom validations, directives can be used.¬†
  • Arguably, this method is the simplest way to create an Angular App.¬†

Reactive Form Approach 

  • This approach is the programming paradigm oriented around data flows and propagation of change.¬†
  • With Reactive forms, the component directly manages the data flows between the form controls and the data models.¬†
  • Reactive forms are code-driven, unlike the template-driven approach.¬†
  • Reactive forms break from the traditional declarative approach.¬†
  • Reactive forms eliminate the anti-pattern of updating the data model via two-way data binding.
  • Typically, Reactive form control creation is synchronous and can be unit tested with synchronous programming techniques.¬†

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Form Control

Form_Controls

Form Control is a class that enables validation. For each input field, an instance of this class is created. These instances help check the values of the field and see if they are touched, untouched, dirty, pristine, valid, invalid, and so on.

Form Group

Form_Groups

FormGroup class represents a group of controls. A form can have multiple control groups. The Form Group class returns true if all the controls are valid and also provides validation errors, if any.

Demo

In this demo, we’ll be creating a User Registration form consisting of four fields, viz, Firstname, Lastname, Email ID, and Password. 

But before creating a form, create a component using the Angular CLI and provide the name of your choice. In this case, we‚Äôve created a component called ‚ÄúformComponent.‚ÄĚ In the template-driven approach, the form‚Äôs module needs to be imported into the app.module.ts file. Go ahead and import it.¬†

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

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

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { NewComponentComponent } from './components/new-component/new-component.component';

import { FormComponentComponent } from './form-component/form-component.component';

@NgModule({

  declarations: [

    AppComponent,

    NewComponentComponent,

    FormComponentComponent,

  ],

  imports: [

    BrowserModule,

    AppRoutingModule,

    FormsModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

We’ve highlighted the code for better visibility. 

Once created, follow the step-by-step instructions to create your form.

Learn the concepts such as TypeScript, Bootstrap Grid System, dependency injections, SPA, forms, pipes, promises, observables, and Angular class testing with the Angular Certification Training Course.

Step1: Form Creation

Create a form tag within a div tag to create the four fields. 

<div class="container">

    <h1>User Registration</h1>

    <form>

        <div class="form-group">

            <label for="firstname">FirstName</label><br>

            <input type="text" name="firstname" class = "form-control" ngModel>

        </div>

        <pre></pre>

        <div class="form-group">

            <label for="lastname">LastName</label><br>

            <input type="text" name="lastname" class = "form-control"    ngModel>

        </div>

        <pre></pre>

        <div class="form-group">

            <label for="email">EmailID</label><br>

            <input type="text" name="email" class = "form-control" ngModel>

        </div>

        <pre></pre>

        <div class="form-group">

            <label for="password">Password</label><br>

            <input type="text" name="password" class = "form-control" ngModel>

        </div>

        <pre></pre>

        <button class="btn btn-primary" type="submit">Submit</button>

    </form>

</div>

Once served, the browser looks like this: 

Form_Creation

Step2: Adding Angular Form Controls

When you inspect the form, classes like ng-untouched, ng-pristine, and ng-valid are added. This indicates that Angular has recognized the form tag and has added the classes to the form as well as the fields. By adding the ngModel directive in the input tag, form controls are added to every input field. 

Form_Controls-Angular_Forms

The form has an output property attached to it called ngSubmit. This property can be bound with a method called ‚ÄúSubmit().‚ÄĚ Once submitted, this method is called.¬†

<form (ngSubmit)="submit()">

The submit method can be defined in the component, i.e., form-component.component.ts file.

import { Component, OnInit } from '@angular/core';

@Component({

  selector: 'app-form-component',

  templateUrl: './form-component.component.html',

  styleUrls: ['./form-component.component.css']

})

export class FormComponentComponent {

  submit(){

    console.log("Form Submitted !")

  }

}

The output is seen on the console: 

Form__Submission

Step3: Getting the JavaScript Object Representation

To generate the JavaScript Representation, another directive called NgForm is assigned to a template variable. 

<form #login = "ngForm" (ngSubmit)="submit(login)">

Consequently, update the submit() method in the .ts file as well. 

export class FormComponentComponent {

  submit(login){

    console.log("Form Submitted !",login)

  }

}

JavaScript_Representation

Once submitted, the message is printed and along with it, the Ngform object is obtained indicating the JavaScript Representation of the form. Getting this representation makes form validation easy. 

If you observe closely, the value object includes the form controls for the input fields. 

Step4: Angular Form Validation

One way to ensure that all the fields are filled correctly is by disabling the submit button in case the fields aren’t filled. Apart from this, you can also specify certain properties in your input tag for the corresponding input field. 

Let’s say, that the fields can’t be empty and the form only accepts names with a minimum length of 2 and a maximum length of 7.

<input required minlength="2" maxlength="7" type="text" name="firstname" class = "form-control" ngModel>

To check this, we’ve submitted the form without filling the FirstName field and evidently, an error can be seen. 

Control_Forms

So you can leverage the form control objects to ensure field validation and display a message when an error occurs. 

To do that, you need to access the form control objects and for that, create a template variable for the field and assign it to the form control object. 

<input required minlength="2" maxlength="7" type="text" name="firstname" class = "form-control" #name="ngModel" ngModel>

Here, the variable name receives the form control object. 

When submitted without filling the FirstName field, the invalid property is set to true. 

Form_Validation.

This helps us use this property to alert the user with the help of the simple ‚Äėif‚Äô logic.¬†

<div class="form-group">

            <label for="firstname">FirstName</label><br>

            <input required minlength="2" maxlength="7" type="text" name="firstname" class = "form-control" #name="ngModel" ngModel>

            <div *ngIf="name.touched && name.invalid" class="alert alert-danger">

                <p *ngIf="name.errors.required">Username Required!</p>

                <p *ngIf="name.errors.minlength">Sorry! Short Username</p>

            </div>

        </div>

The ngIf directive is used to check for the properties. Depending on the error, the corresponding message is displayed. 

Form_Validation-Angular_Forms

Enroll for the Angular Certification Training Course and gain in-depth knowledge of concepts like TypeScript, Bootstrap Grid System, and more!

Next Steps

We hope that this article on Angular Forms has helped you gain a brief insight into the concept of Forms. But to learn more about Angular in its entirety, a valid certification is highly recommended and could catalyze your coding career. Simplilearn's Angular Certification Training Course will help you master front-end web development with Angular. 

You will gain in-depth knowledge of concepts like facilitating the development of single-page web applications, dependency injection, typescript, components, and directives with this Angular Course. You will also have the opportunity to apply your skills by building a real-time application.

If you have any questions or feedback, let us know in the comments section of this ‚ÄėWhat is Angular‚Äô article. Our experts will get back to you immediately.

About the Author

Chinmayee DeshpandeChinmayee Deshpande

Chinmayee is a Research Analyst and a passionate writer. Being a technology enthusiast, her thorough knowledge about the subject helps her develop structured content and deliver accordingly.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.