How to Implement Reactive Forms Using Angular 6 Application

Introduction

In this article, we are going to create reactive forms using angular 6 application. Before proceeding further, I would recommend that you will understand. how to create an angular application and configure the route URLs.

There are two ways to create forms in Angular.

1] Template Driven forms
The name implies Template Driven forms are heavy on the form template meaning we create the form in HTML. Template Driven forms are easy to understand and build. they’re great for creating Simple form. however, building complex forms using a Template Driven approach is not suitable. as the HTML can get very complicated.

2] Reactive forms
The reactive forms/Model Driven forms, allow us to build the form completely in code. this is more flexible and has many benefits over template forms. for example, it’s easy to add form input elements. and add validation at runtime based on the decisions made in code and validation is in a component class.

These are the two classes that we use to create the form control tree.
1] FormGroup
2] FormControl

So, we will proceed to create the whole FormControl tree in the component class code.

Create Two Form Controls

Now, We will be creating a simple reactive form with two form controls.

1] Full Name
2] Email

simple reactive form in angular 6

Now, let’s go ahead and create this form group model. in our create-employee-component.ts class.

First, let’s import FromGroup and FromControl types from angular forms. In the component class and then create a new instance of the form group class.

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

@Component({
  selector: 'app-create-employee',
  templateUrl: './create-employee.component.html',
  styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {
 
  employeeForm: FormGroup;

  constructor() { }

  ngOnInit() {
    this.employeeForm = new FormGroup({
      fullName: new FormControl(),
      email: new FormControl()
    });
  }
}

So this.employeeForm assigns the new FormGroup and to the FormGroup constructor class, we pass an object to form controls as part form group. so, we specify a key is a full name and value is an instance of a form control class.

Similarly, another key-value pair key. in this case, is email and another instance of the form control class.

If you see the definition of this form group constructor.

constructor(controls: { [key: string]: AbstractControl;},
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);

The first parameter controls. it represents a collection of child controls that, we want in the form group. that we are creating and each child control represents a key and a value. the key is a string which is the name of the control that we are creating and value is of type abstract control.

The form control class and form group class derived from this abstract control class. so, the inheritance relationship allows us. to pass a form control as a value to the FormGroup constructor.

Using View Template

We have our form group model created. Now in the view template, we need to include the required HTML to get this layout. so if we want a form element to input elements their Associated labels and a submit button. we are going to use Bootstrap to style this form.

<form class="form-horizontal">
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h3 class="panel-title">Create Employee</h3>
    </div>
    <div class="panel-body">
      <div class="form-group">
        <label class="col-sm-2 control-label" for="fullName">Full Name</label>
        <div class="col-sm-8">
          <input id="fullName" type="text" class="form-control">
        </div>
      </div>

      <div class="form-group">
        <label class="col-sm-2 control-label" for="email">Email</label>
        <div class="col-sm-8">
          <input id="email" type="text" class="form-control">
        </div>
      </div>

    </div>
    <div class="panel-footer">
      <button class="btn btn-primary" type="submit">Save</button>
    </div>
  </div>
</form>

The create-employee-component.html view template there is no angular in this code. this is pure HTML and some bootstrap classes for styling.

So, first we have the form element and we are styling it where the bootstrap forms horizontal class. inside the form, we have the two input elements and they’re associated labels and in the panel footer.

Using formGroup Directive

The panel body we have an input element and its associated label for full name and another input element. and its associated label for email and then the panel footer in that. we have the submit button. now, we need to bind the HTML form element to its associated form group instance in the component class.

<form class="form-horizontal" [formGroup]="employeeForm">
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h3 class="panel-title">Create Employee</h3>
    </div>
    <div class="panel-body">
      <div class="form-group">
        <label class="col-sm-2 control-label" for="fullName">Full Name</label>
        <div class="col-sm-8">
          <input id="fullName" type="text" class="form-control" formControlName="fullName">
        </div>
      </div>

      <div class="form-group">
        <label class="col-sm-2 control-label" for="email">Email</label>
        <div class="col-sm-8">
          <input id="email" type="text" class="form-control" formControlName="email">
        </div>
      </div>
    </div>
    <div class="panel-footer">
      <button class="btn btn-primary" type="submit">Save</button>
    </div>
  </div>
</form>

In the HTML, we have the form element and in the component class. we have its corresponding form group instance. so, we want to bind this form element to this FormGroup instance and then, we use the FormGroup directive.

Similarly, we want to bind the input element to its associated form control instance. for that, we use FormControlName directive. and the same thing with the Email input element.

First, let’s bind this form element to its associated form group instance. the name of the property that holds the form Group instance is employeeForm. so, we are binding property using the directive is form group.

Then, we want to bind this form element to the employee form property. which holds a reference to a form Group instance along the same lines. let’s bind this full name and Email input field.

Let’s save all our changes and take a look at this error message can’t bind to FormGroup.

error message can't bind to form groups in angular

We are getting this error is that both these directives. FormGroup and form control name provides the reactive forms module. and we have not imported this the module within our angular application.

Then within the root application module.app.ts module import reactive forms module.

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

Now, the page is properly displayed without any errors.

display form in angular 6

Bind ng-submit Event

Let’s see, how to access the data that we filled on this form in the component class. this Save button, when we click this button submit event is raise and the form is submitting. so let’s handle the submit event by using ng submit directive on the form element.

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

The form element let’s bind to ng-submit event if you want to bind to own submit method.

Inside a component class so let’s create the method is not going to return anything. the return type is void on submit. we want to log this employee form. which is a form group instance we don’t log the entire form group we just want to log its value property.

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

@Component({
  selector: 'app-create-employee',
  templateUrl: './create-employee.component.html',
  styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {
 
  employeeForm: FormGroup;

  constructor() { }

  ngOnInit() {
    this.employeeForm = new FormGroup({
      fullName: new FormControl(),
      email: new FormControl()
    });
  }
  onSubmit(): void {
  console.log(this.employeeForm.value);
}
}

And see what we get let’s save all our changes and then take a look at the browser. let’s fill out this form and click the Save button. the form group value property lock to the console, as you can see it contains each form control name and its associated value.

reactive form in angular 6

Thank you for reading this article and I hope you get started your application using Angular 6. and also read more articles related to mechanical

Leave a Reply

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