为什么我一直收到此错误?我想我做的一切都好吗?
" EXCEPTION:未捕获(承诺):TypeError:value.forEach不是函数 TypeError:value.forEach不是FormArray.setValue中的函数"
组件类:
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>
解决方案:
FunStuff没错,我无法使用setValue ....所以我删除了它。问题解决了哈哈。我改变了一些事情,我不确定我做了什么,它基本上是蛮力的试验和错误几个小时,但后来它工作了! :)
这是工作版!
jobDetails: FormGroup;
constructor(private formBuilder: FormBuilder){
this.jobDetails = formBuilder.group({
techs: formBuilder.array([
formBuilder.control(''),
formBuilder.control('')
])
});
}
新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>
答案 0 :(得分:8)
setValue 方法采用简单值:
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']
});
答案 1 :(得分:0)
因为您正在构造函数中执行此操作。否则,您需要考虑清空FormArray。
this.techFormArray.forEach((item, idx) => this.jobDetails.get('techs').setControl(idx, item));