Managed / Reactive Forms Model: Auto Mapping Model to FormGroup?

Is there a way to automatically create a FormGroup from a model? If I have a model with multiple properties:

Model: Person

firstName: string,
lastName: string,
street: string
country: string
....

      

and I want to create a simple FormGroup out of it:

Form: FormGroup

firstName: FormControl,
lastName: FormControl,
street: FormControl,
country: FormControl
....

      

It seems to me "dirty" to explicitly define for each property in the FormControl / FormGroup / FormArray model:

formBuilder.group({
  firstName: person.firstName,
  lastName: person.lastName,
  street: person.street,
  country: person.country,
  ...
});

      

Every time the API from the backend changes, I need to customize the model and display of the form. Is there some kind of generator that helps me automate the display / creation of the FormGroup?

+3


source to share


1 answer


formBuilder.group({});

person.forEach(
        (prop) => {
            formBuilder.addControl(prop , new FormControl(person[prop], Validators.compose([ Validators.required])));
        }
    );

      



Not a complete solution, because the validators will necessarily change for each property.

0


source







All Articles