Luis
Luis

Reputation: 2143

How to iterate through controls array property from Forms in Angular

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

Upvotes: 2

Views: 10038

Answers (1)

dev-dan
dev-dan

Reputation: 6283

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.

Upvotes: 7

Related Questions