Angular – Using Form Builder

We can use formbuilder rather than declaring each component and form group new ourselves.

This relies on us adding the import “FormBuilder from @angular/forms

We then use this by utilizing the constructor:


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

export class OurComponent implements OnInit {
   customerForm: FormGroup;
   customer: Customer = new Customer();

   constructor(private fb: FormBuilder) { }

   ngOnInit(): void {
      this.customerForm = this.fb.group({
         firstName: 'default'
      });
   }
}

or instead of “firstName: ‘default'” you could use “firstName: {value: ‘default’, disabled: false}” this allows you to pass an initial state to the item. Maybe more importantly we can use an array syntax instead which allows us to pass in validators i.e. firstName: [‘default’, [Validators.required]]. In this final example we are using one of the angular built in validators but we can also define and use our own. As you can see this can be an array of multiple comma separated validators.

Leave a Reply

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