3

I have the following problem I need to iterate through the controls property of a Form in Angular using a forEach loop. I am writing the following code:

const arr = this.bankForm.controls;
arr.forEach((element: {[key: string]: AbstractControl}) => {

});

And I have the next error:

enter image description here

Luis
  • 2,006
  • 5
  • 31
  • 47

1 Answers1

7

Here is one way you could iterate through the controls

Solution

Object.keys(this.bankForm.controls).forEach((control: string) => {
    const typedControl: AbstractControl = this.bankForm.controls[control];
    console.log(typedControl) 
    // should log the form controls value and be typed correctly
});

This is because the Object.keys();returns an array of the the key values which you can then iterate over using the the forEach(); array method.

Documentation

forEach() method. / Object.keys method. / Angular Form Controls.

Edit

control will always be a string coming from the forEach();, so what I would do is try declaring something new below of the correct type. See above. That makes my IDE recognise it's a form control so will hopefully meet your tsconfig.

devDan
  • 5,969
  • 3
  • 21
  • 40