angularangular6angular-formsangular-formbuilder

How to check if a control exist in form


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. However, my service is returning more fields (EmployeeId, Name, Department etc.) than the form has controls. How do I skip those fields which are not used in the 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: ''
});

Solution

  • you can use patchValue for set value

    this.employeeForm.patchValue(res);