Angular : How to check if some control exist in form or not

Sunil Kumar picture Sunil Kumar · Jun 29, 2018 · Viewed 13.3k times · Source

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: ''
});

Answer

baelx picture baelx · May 6, 2020

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