Angular 2 - How to automatically bind object values to related to Form Controls?

Hitesh picture Hitesh · Feb 22, 2017 · Viewed 24.2k times · Source

I'm using model driven forms and I'm searching a better way to bind the data to related to formControlName's because I have more than 25 fields on my form and I don't want to have to write that code for all fields as I have written for below.

Template:

<input type="text"
       class="form-control"
       formControlName="firstName"
       name="firstName"
       placeholder="First Name"
       required>

Component:

this.refferalService.getReferringDataEdit(id).subscribe(
  result => {
    this.referringData = result.responseObject;
    this.refferalForm.patchValue({ 
      firstName: this.referringData.firstName 
    })
  }
)

Is there a way to do it "automatically"?

Answer

CruelEngine picture CruelEngine · Feb 22, 2017

You can do it Like this :

import {FormGroup,FormBuilder,FormControl} from '@angular/forms';

export class formComponent{
  myForm : FromGroup
  constructor(fb: FormBuilder){
    this.myForm= fb.group({
        'firstName' : [''],
        'lastName' : [''],
    });
 }
 onSubmit(value:string){
   console.log(form);
 }
}

Later in your HTML use it like :

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<input type="text" placeholder="FirstName" [formControl] = "myForm.controls['firstName']">

<input type="text" placeholder="LastName" [formControl] = "myForm.controls['lastName']">
<button type="submit">Submit</button>
</form>

and bind it with (ngSubmit) . So whenever you hit the submit , the value will be reflected in myForm.value . myForm will store the form as key/value pairs.

In the console , your output will be :

Object : 
firstName:....
lastName: ...

You can Refer to : http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/

EDIt: Since the requirement was to save the data from the service:

In your subscribe just do like this : this.refferalForm.setValue(this.referringData); setValue expects an object with key/value Pairs