angular - FormControl 值是否可以是数组?

标签 angular angular-reactive-forms form-control formarray

我正在研究 Angular Reactive 表单。这是我的组件类代码:

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 - FormControl 值是否可以是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47767798/

相关文章:

node.js - 未处理的 promise 拒绝 : Cannot set headers after they are sent to the client

javascript - 如何在 Angular Reactive Form 的嵌套数组字段中构建字段数组?

javascript - 如何创建具有多个输入字段的 Angular 2 自定义组件

reactjs - 在表单控件中 react 引导只读输入

css - Angular2 - 添加属性

css - Angular 单元测试-使用Enter键触发ngSubmit失败

angular - 无法读取未定义的属性 'ngModule'

angular - 在angular2中设置无效的无效表单控件

angular - 如何向嵌套表单组添加新的表单控件?

Angular - 如何在 ngFor 循环表中使用 formcontrol