Angular 11 Forms Tutorial: The Complete Guide

2
36
Angular 7 Forms Tutorial Example From Scratch

In this example, we will use Reactive forms. Reactive forms provide the model-driven approach to handle the form inputs whose values change over time. 

Angular 11 Forms

Reactive forms use a specific and immutable approach to managing the state of the form at a given time. Each change to the form state returns the new state, which maintains the integrity of a model between the changes.

Reactive forms also provide a straightforward path to testing because you are assured that your data is consistent and predictable when the request has been made.

Step 1: Install Angular 11 using Angular CLI.

If you have not upgraded the Angular CLI, you can check out this How To Update Angular CLI To Latest Version

Type the following command to install Angular.

ng new ng7forms
cd ng7forms
ng serve

Angular 7 Forms Tutorial Example

Now, go inside the ng7forms folder and create open the folder inside VSCode.

cd ng7forms
code .

Step 2: Install Bootstrap 4 in Angular

We can install Bootstrap 4 using the following command.

npm install bootstrap --save

Now, include the bootstrap 4 inside the angular.json file inside the styles array.

"styles": [
    "./node_modules/bootstrap/dist/css/bootstrap.min.css",
    "src/styles.css"
],

Save the file and start the dev server using the following command.

ng serve -o

You can see one browser window will open at this URL http://localhost:4200/.

Step 3: Registering the Reactive Forms Module

We can use the reactive forms by importing ReactiveFormsModule from the @angular/forms package and adding it to your app.module.ts file’s imports array. So add the module inside the app.module.ts file.

// app.module.ts

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

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})

Step 4: Add FormControl class

The FormControl class is the fundamental building block when using reactive forms.

Therefore, if we want to register the single form control, we need to import the FormControl class into our component and create a new instance of form control to save it as the class property.

Now, modify the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 email = new FormControl('');
}

Use the constructor  FormControl to set its initial value, the email, which is an empty string.

By creating this control in your component class, you will get immediate access to listen, update, and validate the state of the form input, and in our case, it is email.

Step 5: Registering the control into the template

After creating control in the component class, you must associate it with the form control element.

Then, update that template with a form control using the formControl binding provided by a FormControlDirective included in the ReactiveFormsModule.

<div class="container">
  <label>
    Email:
    <input type="text" [formControl]="email">
  </label>
</div>

Using a template binding syntax, the form control is now registered to an email input element in a template.

So a form control and the DOM element communicate with each other like the view reflects the changes in the model, and the model demonstrates the changes in the view. So this kind of feature is called a two-way-data binding.

Step 6: Controlling the form value

You can display the value in these ways:

  1. Through the valueChanges observable, you can listen for changes in the form’s value in the template using AsyncPipe or the component class using the subscribe() method.
  2. The value property gives you a snapshot of the current value.

So basically, we can achieve the two-way data binding kind of functionality.

<div class="container">
  <label>
    Email:
    <input type="text" [formControl]="email">
  </label>
  <p>
    Value: {{ email.value }}
  </p>
</div>

Angular 7 Forms Example

Step 7: Updating the form control value

Reactive Forms have the methods to change the control’s value programmatically, allowing us to update the value without any user interaction.

For example, the form control instance provides the setValue() method that updates a value of the form control and validates the structure of a value provided against the control’s structure.

Write the following code inside the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  email = new FormControl('');

  updateEmail() {
    this.email.setValue('ankit@appdividend.com');
  }
}

Also, update the view app.component.html file.

<div class="container">
  <div class="form-group">
    <label>
      Email:
    </label>
    <input type="text" [formControl]="email" />
  </div>
  <div class="form-group">
    <button (click)="updateEmail()" class="btn btn-dark">Update Email</button>
  </div>
  <p>
    Value: {{ email.value }}
  </p>
</div>

Type the email value inside the textbox to display the current typed value. Now, click the update email button, which will change the textbox and display values.

That’s it for this tutorial.

2 Comments

  1. hello,
    why do you publish google video ad. when video started my system getting slow and slow. is it not enough to show normal google ad ? if you want more and more visitor then remove it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.