Angular
Building RealWorld, Production-Quality Apps with Angular

Learn To: Use FormBuilder to Create & Manage Forms

PRO

I finished! On to the next chapter

Outline

Quite a few front-end web apps are form-intensive. Angular introduces a new way to create forms called Reactive Forms, aka Model-Driven forms. A few advantages of using Reactive Forms is that you can unit test the form validation logic, and tap into FormGroup and FormControl Observable-based API. Since they are Observables you are able to subscribe to the stream and use functional programming operators such as map, reduce, and filter to name a few.

Below is a simplified version of our login / register form. We have three FormControls: username, email, and password. These controls are grouped together in our formGroup called authForm.

// we set formGroup to authForm
<form [formGroup]="authForm" (ngSubmit)="submitForm()">

    <fieldset class="form-group">
        <input
            // set control name
            formControlName="username"
            placeholder="Username"
            class="form-control form-control-lg"
            type="text"
            *ngIf="authType == 'register'" />
    </fieldset>

    <fieldset class="form-group">
        <input
            // set control name
            formControlName="email"
            placeholder="Email"
            class="form-control form-control-lg"
            type="text" />
    </fieldset>

    <fieldset class="form-group">
        <input
            // set control name 
            formControlName="password"
            placeholder="Password"
            class="form-control form-control-lg"
            type="password" />
    </fieldset>

    <button class="btn btn-lg btn-primary pull-xs-right" type="submit">
        Submit
    </button>

</form>

Below we create an instance of FormGroup and use FormBuilder to create a form group.

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

@Component({
  selector: 'auth-page',
  templateUrl: './auth.component.html'
})
export class AuthComponent {
    // creates instance of FormGroup called authForm
  authForm: FormGroup;

  constructor(
    private fb: FormBuilder
  ) {
    // use FormBuilder to create a form group
    this.authForm = this.fb.group({
      'email': [' ', Validators.required ],
      'password': [' ', Validators.required ]
    });
  }

  submitForm() {
    let credentials = this.authForm.value;
    console.log(credentials);
  }
}

This is a rather simple explanation and example meant as a quick introduction to Reactive forms. Feel free to check out Angular's tutorial on more complex forms!