Angular2 set value for formGroup


So I have a complex form for creating an entity and I want to use it for editing as well I am using new angular forms API. I structured the form exactly as the data I retrieve from the database so I want to set the value of the whole form to the data retrieved here is an example to what i want to do:

this.form ={
      b : [ "", Validators.required ],
      c : [ "", Validators.required ],
      d : [ "" ],
      e : [ [] ],
      f : [ "" ]

PS: NgModel doesn't work with new forms api also i don't mind using one way data binding in template as in

<input formControlName="d" value="[data.d]" />

that works but it would be a pain in case of the arrays

This question is tagged with angular angular2-forms

~ Asked on 2016-07-29 09:45:59

The Best Answer is


To set all FormGroup values use, setValue:

  formControlName1: myValue1, 
  formControlName2: myValue2

To set only some values, use patchValue:

  formControlName1: myValue1, 
  // formControlName2: myValue2 (can be omitted)

With this second technique, not all values need to be supplied and fields whos values were not set will not be affected.

~ Answered on 2016-09-28 16:06:09


For set value when your control is FormGroup can use this example

      latitude: position.coords.latitude,
      longitude: position.coords.longitude

~ Answered on 2017-12-26 16:45:15

Most Viewed Questions: