FormArray TypeError: value.forEach is not a function
19,279
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']
});
Author by
Jus10
Updated on June 27, 2022Comments
-
Jus10 about 2 years
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>
-
Jus10 over 7 yearsSorry, I didn't think it mattered so I didn't include it, but in this scenario I threw in three mock values, in reality I actually don't know the values. I wanted to push them into the array as needed. How do we setValue if we don't know the size of the array?
-
Bazinga over 7 yearsJust push new FormControl. this.techFormArray.push(new FormControl(''))
-
Muhammad Arslan over 6 years@FunStuff can you explain it please, this.techFormArray.push(new FormControl(''))
-
Muhammad Arslan over 6 yearsi have it like this, this.customerForm = this.fb.group({ home: '', addresses: this.fb.array([this.buildAddress()]) }); and want to update addresses values in loop