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) { } ... }
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: [''] });
I then can eventually add validation for each of the fields
contactForm = this.fb.group({ name: ['', Validators.required], email: ['', Validators.required], message: ['', Validators.required] });
Then you would basically use it in the input as
<input type="text" formControlName="name">
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)