Angular 2: ReactiveForm Update Model

I have a reactive form that I would like to directly fill out with my model.

form.component.html

<form [formGroup]="personForm" (ngSubmit)="savePerson()"> <md-card class="app-input-section"> <md-input formControlName="personName" placeholder="Person Name"></md-input> ... many more fields <button md-raised-button color="primary">Save</button> </md-card> </form> 

form.component.ts

 @Component({ selector: 'person', template: 'form.component.html' }) export class FormComponent implements OnInit { person: Person; formBuilder: FormBuilder; personForm: FormGroup; constructor(formBuilder: FormBuilder, personService: PersonService) { this.person = new Person(); this.personForm = formBuilder.group({ personName: [this.person.personName, Validators.required], ... many more properties for form }); } ngOnInit() { console.log('ngOnInit() called'); } savePerson() { this.person.personName = this.personForm.value.personName; ... many more properties set this.personService.savePersontoDB(this.person); } } 

In the savePerson() function, I need to copy the values ​​from personForm FormGroup to a Person object. For a few properties, this is good, however, if I have many properties, this will just be another thing to manage. How can I simplify this code to:

  • personForm values personForm automatically copied to the Person object when form values ​​change.
  • personForm values personForm automatically copied to the Person object when the user clicks the Save button (which subsequently calls the save() function). I mean, you do not need to copy all the individual values ​​of the form to my model object (Person).

What is the best way to do this? Is there any helper I can use, or simpler than that?

Thank you very much

Jt

+5
source share
1 answer

In my application, I did this:

  this.selectedPhysical = <Physical>this.physicalForm.value; 

this maps the fields in the ui form to the base object. So you could:

 this.person = <Person>this.personForm.value; this.personService.savePersontoDB(this.person); 
+3
source

All Articles