Getting started with reactive Forms in Angular 7

In this quick tutorial, I will explain you how to deal with reactive form in Angular 7. If you are tired of using ngModel in your form, that’s great, because at the end of this article, you won’t use it in forms anymore.

To understand reactive form, let’s take a simple example by building a login form.

Basic usage

First you need to add ReactiveFormsModule and FormsModule in the app.module.ts like this:

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';

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

app.module.ts

Then you can create the form:

<form [formGroup]="loginForm">
  <input name="firstName" placeholder="firstName" formControlName="firstName"/><br>
  <input name="lastName" placeholder="lastName" formControlName="lastName"/><br>
  <input name="email" placeholder="Email" formControlName="email"/><br>
  <input type="radio" name="gender" value="male" formControlName="gender"> Male<br>
  <input type="radio" name="gender" value="female" formControlName="gender"> Female<br>
  How many children do you have
  <select class="children" formControlName="children">
    <option value="0">0</option>
    <option value="1">1</option>
    <option  value="2">2</option>
    <option  value="3">3</option>
    <option  value="+3">More than 3</option>
  </select><br>
  <button (click)="sendForm()">
    Send
  </button>
</form>

app.component.html

When you are creating a reactive form, the first thing you need to do is to put the tag ‘form’ with the formGroup parameter. This Parameter is a FormGroup object which will we be initialized in the constructor of the AppComponent by using a formBuilder object. Then, in each field like input, select or textarea, we need to put the attribute ‘formControlName’ that we initialize in the formBuilder like this:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  loginForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.loginForm = this.formBuilder.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', Validators.email],
      gender: ['male', Validators.required],
      children: ['0', Validators.required],
    });
  }

  ngOnInit(): void {
  }

  sendForm() {
    if (this.loginForm.valid) {
      console.log('The form is valid');
    } else {
      console.log('The form is invalid');
    }
  }

}

app.component.ts

In the constructor, we initialize each field by using the name we put in the formControlName attribute. Then, in the array, we can put default values and Validators. Here, we use two simple validators, required and email. This allow us to check if the value is not empty and if it’s an email. To finish, when we send the form we can easily know if it is valid by using ‘this.loginForm.valid’.

Conclusion

To create a reactive form, you have to:

  • Add¬†ReactiveFormsModule and FormsModule in the module
  • Create the form by adding the formGroup attribute
  • Initialize the form with the formBuilder and Validators

Be the first to comment

Leave a Reply

Your email address will not be published.


*