Angular Form Builder and Validators

In the previous few articles, we’ve seen the definition of Reactive Forms and how they are different from template-driven forms. We’ve also seen how to create Reactive Forms using Form Group and Form Controls. Everything will be the same; only the change will be, here we’ll use Form Builder to create Reactive Forms.

How To Use Validators in Angular Reactive Forms Using Form Builders?

Before going into the HTML file and creating a form, the first step is to import ReactiveFormsModule in app.module.ts and add it to the imports array.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from "@angular/forms";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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

export class AppModule { }

Now let’s quickly move into the component class file and import FormBuilder and Validators from @angular/forms.

  • FormBuilder: It’s a helper class of Angular that helps us to build Angular Forms.
  • Validators: It’s a function that is used to add custom validation to an Angular

And now we’re ready to write code to create a Reactive Form using FormBuilder and Validators.

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

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

export class AppComponent {
  title = 'my-app';
  form: any
  constructor(private fb:FormBuilder){ }

  myform = this.fb.group({
    name: ['',Validators.required],
    phone: ['',Validators.compose([Validators.minLength(10),Validators.maxLength(10)])],
    email: ['',Validators.email],
    address: ['',Validators.required]
  })

  clicked(){
    this.form=this.myform.value
  }
}
  • First– inject FormBuilder inside the constructor and name it of your own choice; we used fb.
  • Second– create a group and name it of your own choice; we used myform.
  • Third– define all the formControl inside the curly braces.
  • Fourth- add all the required Validators to each of the

Now let’s move to the HTML file and define all these formControl.

<div>
  <h1>Registration Form</h1> 
  <form [formGroup]="myform">
    <div>
      <input type="text" placeholder="Enter your name" name="name" formControlName="name">
    </div>
    <div>
      <input type="text" placeholder="Enter your mobile number" name="phone" formControlName="phone">
    </div>
    <div>
      <input type="text" placeholder="Enter your email" name="email" formControlName="email">
    </div>
    <div>
      <input type="text" placeholder="Enter your address" name="address" formControlName="address">
    </div>
    <button type="submit" (click)="clicked()" [disabled]="!myform.valid">SUBMIT</button>
  </form>
  <br>
  {{form | json}}
</div>

The HTML code is pretty the same as in the previous article. The only change is in the submit button. In the submit button, we added the disabled attribute and set its value as not equal to myform.valid. Valid is the in-built method that checks the validity of all the Validators that we defined.

Let’s see the difference in the browser. 

Initially (without proper validation):

angular reactive form using form builder example

Finally (with proper validation):

angular reactive form with interpolation using form builder example

The difference is clear now. Lastly, we’ve used interpolation and pipes to display all the valuable information of the form.

Output:

angular reactive form with validations using form builder example

Now let’s see how we can access formControl individually.

clicked() {
  var name = this.myform.get('name')?.value;
  console.log(name)
}

The get and value are the in-built methods that we used to access any individual formControl.

Output:

angular reactive form and console form variables example

Conclusion

We hope you’ve understood all the basic concepts of FormBuilder and Validator. Now we’re ready to develop any business websites and add ReactiveForms on that, and we’re also ready to move on to the advanced topics of Angular.

Leave a Reply

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