DEV Community

Prayatna Bhattarai
Prayatna Bhattarai

Posted on • Updated on

TIL: How to use form builder to create groups in Angular

We can use the formBuilder service to group all the form fields. I start with injecting FormBuilder from angular/forms and inject in my contactComponent

import { FormBuilder } from '@angular/forms';

@Component({
  selector: "contact",
  templateUrl: "./contact.component.html",
  styleUrls: ["./contact.component.css"]
})
export class ContactComponent implements OnInit {
  constructor(private fb: FormBuilder) { }
 ...
}
Enter fullscreen mode Exit fullscreen mode

Since it is a contact form, I have name, email, and message as the form fields. So I create a form group as

 contactForm = this.fb.group({
    name: [''],
    email: [''],
    message: ['']
  });
Enter fullscreen mode Exit fullscreen mode

I then can eventually add validation for each of the fields

contactForm = this.fb.group({
    name: ['', Validators.required],
    email: ['', Validators.required],
    message: ['', Validators.required]
  });
Enter fullscreen mode Exit fullscreen mode

Then you would basically use it in the input as

<input type="text" formControlName="name">
Enter fullscreen mode Exit fullscreen mode

And that's it. There seems to be a lot of things that you can do with the form, but that will be a post for another day.

Top comments (0)