How to check if a control exist in form
Asked Answered
P

3

18

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: ''
});
Perennate answered 29/6, 2018 at 8:24 Comment(0)
S
7

you can use patchValue for set value

this.employeeForm.patchValue(res);
Secular answered 29/6, 2018 at 8:29 Comment(0)
B
38

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

Bresnahan answered 6/5, 2020 at 20:22 Comment(0)
A
15

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

Advanced answered 2/7, 2018 at 0:29 Comment(0)
S
7

you can use patchValue for set value

this.employeeForm.patchValue(res);
Secular answered 29/6, 2018 at 8:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.