Angular 8 Forms Tutorial | Angular Reactive and Template Forms Example

Like Tweet Pin it Share Share Email
Angular 8 Forms Tutorial | Angular Reactive and Template Forms Example

Angular 8 Forms Tutorial | Angular Reactive and Template Forms Example is today’s topic. If you are new to Angular 8, then check out my Angular 8 Tutorial. If you do not know how to upgrade to Angular 8 via Angular CLI, then check out my Angular 8 Upgrade tutorial. Managing the user input with forms is the cornerstone of many web applications.

Web app use forms to enable the users to log in, to update a profile, to enter sensitive information, and to perform many data-entry tasks.

Angular 8 Forms Tutorial

Angular provides two different approaches for managing the user input through the forms.

  1. Reactive approach
  2. Template-driven approach

Both reactive and template-driven forms share underlying common building blocks which are the following.

  1. FormControl: It tracks the value and validation status of the individual form control.

  2. FormGroup: It tracks the same values and status for the collection of form controls.
  3. FormArray:It tracks the same values and status for the array of the form controls.
  4. ControlValueAccessor: It creates the bridge between Angular FormControl instances and native DOM elements.

Reactive forms in Angular 8

Reactive forms or Model-driven forms are more robust, scalable, reusable, and testable. If forms are the key part of your application, or you’re already using reactive patterns for building your web application, use reactive forms.

In Reactive Forms, most of the work is done in the component class.

Template-driven forms in Angular 8

Template-driven forms are useful for adding the simple form to an app, such as the email list signup form. They’re easy to add to a web app, but they don’t scale as well as the reactive forms.

If you have the fundamental form requirements and logic that can be managed solely in the template, use template-driven forms.

In template-driven forms, most of the work is done in the template.

Example of Template-driven form in Angular 8

Okay, now let’s install the fresh Angular 8 application.

Then go to an app.module.ts file and add the following code.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the above file, we have imported the FormsModule from the @angular/forms library.

Now, we can use the FormsModule inside our app.component.ts file.

// app.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
   constructor() { }
   ngOnInit() {
   }
   onClickSubmit(formData) {
      alert('Your Email is : ' + formData.email);
   }
}

In this file, we have defined on onClickSubmit function, which will trigger when the user clicks the submit button on the form. The function also accepts one argument called formData, which is the object of the entire form values.

Through that formData object, we can access all the form field values. In our case, I only need the user’s email id. In the general scenario, we want to pass that object to the POST request to the backend server to store the user’s data.

Now, only remaining thing is to write the HTML of the app component. So, write the following code inside the app.component.html file.

<form #login = "ngForm" (ngSubmit) = "onClickSubmit(login.value)" >
  <input type = "text" name = "email" placeholder = "email" ngModel>
  <br/>
  <input type = "password" name = "pwd" placeholder = "password" ngModel>
  <br/>
  <input type = "submit" value = "submit">
</form>

We have created the web form with input tags having email, password and the submit button. We have assigned a type, name, and placeholder attributes to it.

In the template driven forms, we need to create a model form controls by adding the ngModel directive and the name attribute. Thus, whenever we want Angular to access our data from forms, add ngModel to that tag as shown above. Now, if we have to read an email and password, we need to add a ngModel across it.

If you close look at the form, we have also added the ngForm to the #login. The ngForm directive needs to be added to a form template that we have created.

Atlast, We have also added the function onClickSubmit and assigned login.value to it.

Save the file and start the angular development server by the following command.

ng serve -o

You will see the browser screen with the login form. Now fill the form and you will see something like the following image.

Angular 8 Forms Tutorial | Angular Forms Example

So, that is it for the Template-driven forms in Angular 8.

Model-driven or Reactive Forms in Angular 8

In the model-driven form, we need to import a ReactiveFormsModule from @angular/forms and use the same in the imports array.

There is a change which goes in app.module.ts. See the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the app.component.ts file, we need to import the few modules for the model-driven form. For example, import { FormGroup, FormBuilder } from ‘@angular/forms’.

See the following app.component.ts file.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  angForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.createForm();
  }
  createForm() {
    this.angForm = this.fb.group({
      email: [''],
      password: ['']
    });
  }
  onClickSubmit(email, password) {
    alert('Your Email is : ' + email);
  }
   ngOnInit() {
   }
}

In the above code, we have used a FormBuilder to create a form and initialize the value of two fields which is empty.

We have also defined one function called onClickSubmit() which accepts the two parameter email and password.

So,  when the user pressed the submit button, we got the values here and then we send these values with the POST request to the backend server.

Finally, write the app.component.html file.

<form [formGroup]="angForm">
  <input type = "text" 
        name = "email" 
        placeholder = "email" 
        formControlName="email" 
        #email>
  <br/>
  <input type = "password" 
        name = "pwd" 
        placeholder = "password" 
        formControlName="password" 
        #password>
  <br/>
  <input type = "submit" 
          value = "submit" 
          (click) = "onClickSubmit(email.value, password.value)" >
</form>

Now, save the above file and go to the Angular app and you will see the same output as we have got in the template-driven approach.

One of the advantages of the Model-driven approach is that the Validations become very easy.

Finally, we have seen both the approaches and Angular 8 Forms Tutorial | Angular Reactive and Template Forms Example is over.

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *