Using the FormBuilder service to generate controls
In the previous section, we successfully created reactive forms using form groups, form arrays, and form controls. However, as we can see from the syntax, creating forms becomes repetitive. We are always instantiating new instances of form controls, form arrays, and form groups, and this is not ideal in larger forms. FormBuilder
provides the solution for this issue.
This is a service that can be injected into our components to generate groups, controls, and arrays without instantiating new ones. To create a reactive form using FormBuilder
, we will be following the next steps:
- We will be transforming the form in the previous section using
FormBuilder
. The first step is to import theFormBuilder
service into our component from@angular/forms
:import { FormBuilder } from '@angular/forms';
- The next step is to inject the
FormBuilder
service into our component:export class HeroComponent implements OnInit {
powerFormArray...