【问题标题】:Whether a FormControl value can be an array?FormControl 值是否可以是数组?
【发布时间】:2018-05-25 20:29:38
【问题描述】:

我正在研究 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 处理。谢谢

【问题讨论】:

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


    【解决方案1】:

    最后我解决了,答案是肯定的。 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.
    
        }));
    

    【讨论】:

      猜你喜欢
      • 2019-09-22
      • 2017-01-31
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2013-09-19
      • 1970-01-01
      相关资源
      最近更新 更多