In a previous tutorial, we talked about building Template Driven forms in Angular. Even though this is great for small forms that don’t contain any complex business logic, it’s isn’t very scalable. The preferred solution to this is Reactive Forms. They allow for the logic to be placed in the component, low-level API access and are immutable. That means any changes create a new copy of the data. Click here to gain access to our videos about Angular, React as well as integrations with backend Rest APIs.

Converting to Angular Reactive Forms

Using Reactive Forms means having low-level access to the Forms API. Temple Driven forms use an abstraction on top of this API. Let’ start off by adding the React Forms Module to our application.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
imports: [.....
    ReactiveFormsModule],

We add the ReactiveFormsModule to our imports to be able to use it throughout our application.

Next, we’ll go to our form and remove the model from the previous tutorial and import FormGroup and FormControl. These allow for the creation of a form object. This is actually the low-level API that is referenced in Template Driven Forms.

import { FormGroup, FormControl, Validators } from '@angular/forms';
export class AppComponent {
  title = 'angFormsDemo';
  subscriberForm = new FormGroup({
    firstName: new FormControl('', [Validators.required]),
    lastName: new FormControl('', [Validators.required]),
    address: new FormControl(''),
    email: new FormControl('', [Validators.required]),
    promotions: new FormControl('')
  });
  onSubmit() {
    console.log(this.subscriberForm);
    alert(JSON.stringify(this.subscriberForm.value));
  }
}

We also add validators to specify what validation we want on our input. Inside of the template, we’ll remove all of the references to the model and add references to the FormControls. We’ll also make sure the form submit button is disabled when it is not valid.

<form [formGroup]="subscriberForm" (ngSubmit)="onSubmit()">
    <mat-form-field>
      <input matInput placeholder="First Name" formControlName="firstName" required id="firstName">
    </mat-form-field>
    <mat-form-field>
      <input matInput placeholder="Last Name" formControlName="lastName" required id="lastName">
    </mat-form-field>
    <mat-form-field>
      <input matInput placeholder="Address" formControlName="address" id="address">
    </mat-form-field>
    <mat-form-field>
      <input matInput placeholder="Email" email formControlName="email" required  id="email">
    </mat-form-field>
    <mat-checkbox id="promotion" formControlName="promotions">Get Promotions</mat-checkbox>
    <br />
    <button mat-flat-button color="primary" [disabled]="!subscriberForm.valid">Submit</button>
  </form>
Disabled Form

Disabled Form

Using Reactive Form FormBuilder

When building Reactive Forms, you also have the option to use a built-in service called FormBuilder. This option is generally used when building multiple forms. First, import FormBuilder.

import { Validators, FormBuilder } from '@angular/forms';
export class AppComponent {
  title = 'angFormsDemo';
  subscriberForm = this.fb.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    address: [''],
    email: ['', Validators.required],
    promotions: ['']
  });
  constructor(private fb: FormBuilder) {}
  onSubmit() {
    console.log(this.subscriberForm);
    alert(JSON.stringify(this.subscriberForm.value));
  }
}

That’s it. It’s that simple.

Conclusion

Building Reactive Forms is generally the easier and more scalable way to go. It offers easier access to the API and keeps most of your logic out of the templates. Click here to gain access to our videos about Angular, React as well as integrations with backend Rest APIs.

 

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit