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
To set all FormGroup values use, setValue:
To set only some values, use patchValue:
With this second technique, not all values need to be supplied and fields whos values were not set will not be affected.
That's not true. You just need to use it correctly. If you are using the reactive forms, the NgModel should be used in concert with the reactive directive. See the example in the source.
Though it looks like from the TODO comments, this will likely be removed and replaced with a reactive API.
I have implemented a temporary solution until angular2 support form updateValue
usage:
note: form and data must have the same structure and i have used lodash for deepcloning jQuery and other libs can do as well
Yes you can use setValue to set value for edit/update purpose.
You can refer http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/ to understand how to use Reactive forms for add/edit feature by using setValue. It saved my time
For set value when your control is FormGroup can use this example
As pointed out in comments, this feature wasn't supported at the time this question was asked. This issue has been resolved in angular 2 rc5