Reactive Forms Build With FormBuilder In Angular

We are learning about the reactive ReactiveFormsModule with FormBuilder it is related, don’t know about of FormBuilder can see my previous blog and FormBuilder discussion of deep.

This is when things start to get even better! Instead of explicitly utilising FormGroup and FormControl, we can utilise a magical API that handles everything for us. FormBuilder is here!

First and foremost, we must modify our imports from this:

import { FormControl, FormGroup, Validators } from '@angular/forms';

export class SignupFormComponent implements OnInit {
  user: FormGroup;
  constructor() {}
  ...
}

To this (with additional constructor injection to make this.fb available as the FormBuilder):

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

export class SignupFormComponent implements OnInit {
  user: FormGroup;
  constructor(private fb: FormBuilder) {}
  ...
}

This is due to the fact that user: FormGroup; on our component class is of the FormGroup type. So, what exactly is FormBuilder? It’s simply syntactic sugar that generates FormGroup, FormControl, and FormArray objects for us (ForArray will be covered in a later post). It’s only sugar, but you know what it’s for now.

Let’s change our code so that we may utilise FormBuilder:

// before
ngOnInit() {
  this.user = new FormGroup({
    name: new FormControl('', [Validators.required, Validators.minLength(2)]),
    account: new FormGroup({
      email: new FormControl('', Validators.required),
      confirm: new FormControl('', Validators.required)
    })
  });
}

// after
ngOnInit() {
  this.user = this.fb.group({
    name: ['', [Validators.required, Validators.minLength(2)]],
    account: this.fb.group({
      email: ['', Validators.required],
      confirm: ['', Validators.required]
    })
  });
}

The refactoring is self-explanatory, but we’ll go over it briefly.

Instead of calling new FormGroup(), we inject FormBuilder as fb and create a new this.

fb.group(). It’s only syntactic sugar, but the structure of these is similar to generating the controls and groups on their own. As a result, we have a component class that looks like this:

@Component({...})
export class SignupFormComponent implements OnInit {
  user: FormGroup;
  constructor(private fb: FormBuilder) {}
  ngOnInit() {
    this.user = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      account: this.fb.group({
        email: ['', Validators.required],
        confirm: ['', Validators.required]
      })
    });
  }
  onSubmit({ value, valid }: { value: User, valid: boolean }) {
    console.log(value, valid);
  }
}

Submit a Comment

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

Subscribe

Select Categories