Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model Driven / Reactive Forms: Auto mapping from 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 'dirty' to me, to explicitly define for each property in the Model a FormControl / FormGroup / FormArray:

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

Each time the API from the Backend changes i have to adjust the model AND the form mapping. Is there some kind of generator which helps me to automate the mapping / creation of a FormGroup ?

like image 239
Eike Behrends Avatar asked May 17 '17 07:05

Eike Behrends


1 Answers

formBuilder.group({});

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

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

like image 113
Amit Chigadani Avatar answered Oct 04 '22 18:10

Amit Chigadani