8

Below is my code to get a response from the service. Here I am getting a list of employees.

I need to bind form controls dynamically based on the response of service, my service returning more fields(EmployeeId, Name, Department etc.) than the form has controls. How to skip those which are not used in form control?

this._employeeService.getEmployeeById(this.employeeId).subscribe((res: Response) => {
  this.employeeForm.get('FileUploader').setValue(null);
  for (const field in res) {
    this.employeeForm.controls[field].setValue(res[field]);
  }
});

this.employeeForm = this._fb.group({
  EmployeeId: 0,
  Name: ''
});
Nikita Fedyashev
  • 15,938
  • 11
  • 41
  • 69
Sunil Kumar
  • 749
  • 2
  • 11
  • 23

3 Answers3

17

While there already is an accepted answer, it's worth mentioning that there is indeed a method available just in case it might be useful to those actually wanting a concrete way to verify the existence of a given FormControl within a FormGroup:

contains(controlName: string): boolean


Source: https://angular.io/api/forms/FormGroup#contains

baelx
  • 343
  • 5
  • 8
12

You can use the get method of FormGroup class. Change your iterator in getEmployeeById callback, like that:

for (const field in res) {
  const formControl = this.employeeForm.get(field);

  if (formControl) {
     formControl.setValue(res[field]);
  }
}

Source: https://angular.io/api/forms/FormGroup

Rodrigo
  • 1,735
  • 2
  • 12
  • 18
6

you can use patchValue for set value

this.employeeForm.patchValue(res);
Krishna Rathore
  • 7,755
  • 3
  • 19
  • 43