Reputation: 2520
I have a form built using a FormBuilder with lots control elements and I want to set values to them based on response from server
Currently I'm doing it like this:
this.form.controls['a'].setValue(data.a);
this.form.controls['b'].setValue(data.b);
this.form.controls['c'].setValue(data.c);
this.form.controls['d'].setValue(data.d);
and so on.
Is there a way to do it more neat?
Upvotes: 0
Views: 66
Reputation: 29614
You can use setValue of FormGroup
.
According to the API docs.
It accepts an object that matches the structure of the group, with control names as keys.
You can do:
this.form.setValue({
a:data.a,
b:data.b,
c:data.c,
d:data.d
});
You will need ensure all the control values are present together and they pass any validators
you may have set for your form.
You could also use patchValue function as suggested by @Gunther to fill your form. It can take subsets of form values without validation and tries to match them.
Upvotes: 3