Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = builder.group({       b : [ "", Validators.required ],       c : [ "", Validators.required ],       d : [ "" ],       e : [ [] ],       f : [ "" ]     }); this.form.value({b:"data",c:"data",d:"data",e:["data1","data2"],f:data}); 

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

like image 950
Amgad Serry Avatar asked Jul 29 '16 09:07

Amgad Serry


People also ask

How do you assign a value to a FormGroup?

We use the SetValue to update the FormControl , FormGroup or FormArray . When we use it to update the FormGroup or FormArray the SetValue requires that the object must match the structure of the FormGroup or FormArray exactly. Otherwise, it will result in an error.

How do you set a value in reactive form?

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances. patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls.

How do I find the value of a FormGroup?

FormGroup valueChanges() and statusChanges() To track the value changes and status changes of a form control we need to listen them using subscribe() method. Find the code. In the above code name is the name of form control. Now we can use value changes and status changes to display on UI.

How do I change the default value in FormControl?

If we want to set a default value to our form control, we can pass a default value while instantiating a FormControl in our class. city = new FormControl('Noida'); married = new FormControl(true); In HTML template, we will use these properties with form control.


2 Answers

To set all FormGroup values use, setValue:

this.myFormGroup.setValue({   formControlName1: myValue1,    formControlName2: myValue2 }); 

To set only some values, use patchValue:

this.myFormGroup.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.

like image 133
Stephen Paul Avatar answered Sep 22 '22 14:09

Stephen Paul


You can use form.get to get the specific control object and use setValue

this.form.get(<formControlName>).setValue(<newValue>); 
like image 27
Varadhan Work Avatar answered Sep 20 '22 14:09

Varadhan Work