FormControl 的值是否可以是数组?
Whether a FormControl value can be an array?
我正在研究 Angular 响应式表单。这是我的组件 class 代码:
ngOnInit(){
this.reviewForm = this.fb.group({
'controlArray': new FormArray([])
});
this.showDefaultForm();
}
addForm() {
(<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group({
controlType: control.controlType,
options: control.options,
}));
}
我收到 TypeError: this.validator is not a function with this。我认为这是由于将字符串数组(即 control.options)作为值分配给 FormControl。
如果我将其设为 FormArray,则此错误会解决,但我无法将其作为模板中的 FormArray 处理。请告诉我,如果我不使用 FormArray,我可以将一个字符串数组作为值分配给 FormControl 吗?如果不是,那么如何在模板中将其作为 FormArray 处理。谢谢
最后我解决了,答案是肯定的。 FormControl 的值可以是一个数组。但是为此,您必须将值括在方括号 [ ] 中。此外,对于简单值(非数组),这些方括号是可选的,这意味着您可以将值包含在方括号内或不包含在方括号内。
代码解释:
(<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group({
controlType: control.controlType,
options: [control.options], //previously I was not using square brackets with options value i.e. options: control.options which was wrong.
}));
我正在研究 Angular 响应式表单。这是我的组件 class 代码:
ngOnInit(){
this.reviewForm = this.fb.group({
'controlArray': new FormArray([])
});
this.showDefaultForm();
}
addForm() {
(<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group({
controlType: control.controlType,
options: control.options,
}));
}
我收到 TypeError: this.validator is not a function with this。我认为这是由于将字符串数组(即 control.options)作为值分配给 FormControl。 如果我将其设为 FormArray,则此错误会解决,但我无法将其作为模板中的 FormArray 处理。请告诉我,如果我不使用 FormArray,我可以将一个字符串数组作为值分配给 FormControl 吗?如果不是,那么如何在模板中将其作为 FormArray 处理。谢谢
最后我解决了,答案是肯定的。 FormControl 的值可以是一个数组。但是为此,您必须将值括在方括号 [ ] 中。此外,对于简单值(非数组),这些方括号是可选的,这意味着您可以将值包含在方括号内或不包含在方括号内。
代码解释:
(<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group({
controlType: control.controlType,
options: [control.options], //previously I was not using square brackets with options value i.e. options: control.options which was wrong.
}));