Andrew Graham-Yooll
Andrew Graham-Yooll

Reputation: 2258

Calling a function inside Array.ForEach

I am generating a form in Angular2/Ionic2 and I have followed the dynamic form tutorial on the Angular site. However, for my needs, I need more validations instead of just required. Hence this code.

doGenerateKidsBasicFormWithNameAndAge(params: any){
let kidsData:any = {};

params.forEach(question => {

        kidsData[question.id] = this.doDecideValidation(question)
        });
  return new FormGroup(kidsData);
}

This is the function that decideds what type of validation will be applied.

doDecideValidation(question){
    if(question.type === "text"){
      new FormControl(question || '', Validators.compose([Validators.required, Validators.minLength(question.minLength), Validators.maxLength(question.maxLength), Validators.pattern('[a-zA-Z ]*')]));
    }else if(question.type === "number"){
      new FormControl(question || '', Validators.compose([Validators.required]));
    }else {
      new FormControl(question || '');
    }
  };

When I do this, I get an error.

TypeError: Cannot read property 'setParent' of undefined

Any ideas?

Upvotes: 0

Views: 4369

Answers (2)

Vadim Levkovsky
Vadim Levkovsky

Reputation: 346

Maybe you just need to specify rith this (second parameter in forEach function)?

The invocation context (this) of the forEach function call

Upvotes: 0

Scrambo
Scrambo

Reputation: 629

To go along with my comment, after doing some reading on Typescript Types, and looking at the Forms example you gave, I might have figured out what the problem is.

You have a .forEach() operating on params: any, a variable that may or may not be an array. Try slapping on the [] like so: params: any[], and see if that helps.

Upvotes: 1

Related Questions