Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormArray TypeError: value.forEach is not a function

Why do I keep getting this error? I think I'm doing everything right?

"EXCEPTION: Uncaught (in promise): TypeError: value.forEach is not a function TypeError: value.forEach is not a function at FormArray.setValue"

Component Class:

jobDetails: FormGroup;
techFormArray: FormArray;

constructor(private formBuilder: FormBuilder){

    this.techFormArray = new FormArray([
        new FormControl(''),
        new FormControl(''),
        new FormControl('')
    ]);
    this.jobDetails = this.formBuilder.group({
        techs: this.formBuilder.array([])
    });
    this.jobDetails.setValue({
        techs: this.techFormArray
    });
}

HTML:

<form [formGroup]="jobDetails">
  <div formArrayName="techs" >
    <div style="display: flex; flex-direction: column">
      <div *ngFor="let tech of techFormArray.controls; let i=index">
        <md-checkbox [formControlName]="i">
          {{i}}
        </md-checkbox>
      </div>
    </div>
  </div>
</form>

SOLUTION:

FunStuff had it right, I couldn't use setValue.... so I removed it. Problem solved lol. I changed around a few things, and I'm not sure exactly what I did, it was essentially brute-force trial and error for hours, but then it worked! :)

Here's the working version!

jobDetails: FormGroup;

constructor(private formBuilder: FormBuilder){

    this.jobDetails = formBuilder.group({
        techs: formBuilder.array([
            formBuilder.control(''),
            formBuilder.control('')
        ])
    });
}

New HTML:

    <form [formGroup]="jobDetails">
        <div formArrayName="techs" >
            <div style="display: flex; flex-direction: column">
                <div *ngFor="let tech of jobDetails.controls.techs.controls; let i=index">
                    <md-checkbox [formControlName]="i">
                        {{i}}
                    </md-checkbox>
                </div>
            </div>
        </div>
    </form>
like image 446
Jus10 Avatar asked Dec 16 '16 03:12

Jus10


1 Answers

The setValue method takes simple values:

   this.techFormArray = new FormArray([
        new FormControl(''),
        new FormControl(''),
        new FormControl('')
    ]);

    this.jobDetails = this.formBuilder.group({
        techs: this.techFormArray
    });

    this.jobDetails.setValue({
      techs: ['a', 'b', 'c']
    });
like image 118
Bazinga Avatar answered Nov 03 '22 00:11

Bazinga