我有一个表单数组,它是在从初始值为 false 的服务获取数据后动态设置的。
constructor(){
this.form = this.fb.group({
//...other controls...
addOns: fb.array([])
})
}
ngOnInit(){
this.addonsService.getAll()
.subscribe(result => {
this.addOns = result;
for(let addOn in this.addOns) {
this.form.get('addOns').push(new FormControl(false));
}
});
}
Run Code Online (Sandbox Code Playgroud)
然后我需要根据另一组值设置数组中的值。我努力了
var formArray = this.form.get('addOns') as FormArray;
Run Code Online (Sandbox Code Playgroud)
然后循环过去,但这不起作用
formArray.controls.forEach(c => {
c.setValue(true)
})
Run Code Online (Sandbox Code Playgroud)
我也尝试按索引调用,但这返回未定义
formArray.controls[0].setValue(true);
Run Code Online (Sandbox Code Playgroud)
如果我 console.log() formArray 我会得到预期数量的表单控件。
动态构建后如何设置 formArray 的值?