Angular12 Forms

Forms are used in web applications to process user input. We can employ the forms to do different data entry tasks such as entering user information, logging in, updating information and profiles, and entering sensitive data such as passwords. 

Forms have significant responsibilities in addition to receiving user input and transmitting it to the webserver. These roles include:

  • Validation errors are presented when a user enters erroneous information into a form.

  • Providing data entry security through hiding sensitive data as user inputs.

  • Recognizing any unforeseen mistakes made by the user during data entry, 

  • It instructs the user on how to enter values and which values are required to be entered.

To fulfill all of the user needs and responsibilities that form play, Angular 12 has updated features that assist in:

  • Validating the data entered by the user

  • Observing and presenting changes and reactions to user inputs

  • Providing objects to deal with and encapsulating the input forms.

 

Creating Forms

Form creation is a lot simpler than you think, especially if you are familiar with the Bootstrap classes. The Bootstrap framework has many pre-built CSS classes that allow you to quickly create stunning and responsive forms, saving you time.

To begin, go to the Bootstrap official website and copy the Bootstrap link code, which you should paste into your index.html. This code connects your website to the Bootstrap framework

 

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

 

 

To use FormControl, we will need to import the FormModules and ReactiveFormsModules into our application module. To do this, insert the following code into your AppModule

import {BrowserModule} from '@angular/platform-browser';
import { NgModule} from '@angular/core';
import{AppRoutingModule} from './app-routing.module';
import{AppComponent} from './app.component';
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declaration:[]
      AppComponent,
   ],
   imports:[
   BrowserModule,
   AppRoutingModule,
   FormsModule,
   ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppRoutingModule{}

 

You are now prepared to start creating forms. First, let's talk a little bit about FormGroups and forms controls and how we can use them in our project.

The FormGroups and FormControls

There are two main differences between form groups and FormControls.

First, a form control consists of a single input field into which a user may enter data. The FormGroups, contrary, is made up of numerous form input fields, and the user must enter data into several fields

 

Secondly, a form control verifies a single input form, but a FormGroup validates several input forms.

To demonstrate these differences between the two, let's construct a formControl and a FormGroup.

An example of a Form Control

 

<div class="container mt-3">
   <form>
      <div class="form-group">
         <label for="name">Name</label>
         <input type="text" name="name" formControlName="name" class="form-control" />
      </div>
   </form>
</div>

 

This code will display a single form on the web page prompting you to enter your name

 

An example of a FormGroup

 

<div class="container mt-3">
   <form [formGroup]="PFormGroup">
      <div class="form-group">
         <label for="name">Name</label>
         <input type="text" name="name" formControlName="name" class="form-control" />
      </div>
      <div class="form-group">
         <label for="school">School</label>
         <input type="text" name="name" formControlName="name" class="form-control" />
      </div>
      <div class="form-group">
         <label for="board">Board</label>
         <input type="text" name="name" formControlName="name" class="form-control" />
      </div>
   </form>
</div>

 

The above code will display three input forms on your web browser

How to make forms Submit Data

The code above will only create beautiful forms that will accept the user to input his information; however, we need to submit our information to the webserver for processing or saving for future use. To make our forms submitted, we need to add the following codes:

  • In the <form> opening tag, add the ngSubmit event

<form [formGroup]="personFormGroup" (ngSubmit)="onFormSubmit()"> </form>

 

Next, add the button below your forms but within the form>/form> tags.

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

 

Finally, configure the method.

PFormGroup: FormGroup;
onFormSubmit() {
console.log(this.personFormGroup.value);
}

 

Following the click of the button, the information supplied in the forms will be submitted using the ngSubmit function on the form> tags.

How to Take Care of Form Data

Depending on the sort of forms you use, you may handle your data in one of two ways. You may handle either template-driven or reactive forms.

Reactive forms are beneficial because they give direct and explicit access to the complete forms object model. This method is more testable, useful, and scalable.

When creating a reactive form, you must declare the component class explicitly, where the class implements the form element's input field

 


import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-reactive-favorite-color',
  template: `
    Favorite Color: <input type="text" [formControl]="favoriteColorControl">
  `
})
export class FavoriteColorComponent {
  favoriteColorControl = new FormControl('');
}

 

Template-driven forms- This technique relies on template directives to create and manipulate the chosen object model. This is ideal for building simple forms in an application, such as sign-in and sign-up forms.

To implement the template-driven, we utilize the NgModel Directive to build and control the FormControl as follows

 

import { Component } from '@angular/core';
@Component({
  selector: 'app-template-favorite-color',
  template: `
    Favorite Color: <input type="text" [(ngModel)]="favoriteColor">
})
export class FavoriteColorComponent {
  favoriteColor = '';
}

 

Conclusion

Finally, we have learned how to create angular 12 forms and submit information entered by the user into the forms. In the following chapter, we'll look at how we can validate the information entered by the user.