【问题标题】:Set custom property to all form objects in nested reactive forms structure为嵌套反应式表单结构中的所有表单对象设置自定义属性
【发布时间】:2020-11-20 00:15:43
【问题描述】:

我有一个复杂的角度应用程序的问题。 目前,我有一个大型嵌套的角度反应形式结构,其中包含一个“主”FormGroup,其中包含多个 FormGroup / FormArrays / FormControls。

例如:

 FormGroup: {  
    FormControl: {}  
    FormGroup: {FormGroup: {FormControl...,   FormControl...}}  
    FormArray: [FormGroup {...}, FormGroup{...}]    
...  
}

现在我想将自定义 FormControl / Property 添加到大主窗体的 所有 子窗体。就我而言,它就像“Read-Only: true”。

一种解决方案是将 HTML 中的所有子元素(表单)赋予父表单@Input,因此我必须只向父表单添加一个属性。 但也许有一种我想不到的更顺畅的方法。

非常感谢您的建议或任何解决方案。

【问题讨论】:

    标签: angular forms nested angular-reactive-forms


    【解决方案1】:

    FormGroup 可以遍历控件——它们是对象,但你可以使用 Object.keys——你可以使用递归函数,例如

    setEnabled(formGroup,value)
      {
         Object.keys(formGroup.controls).forEach(x=>{
           const gr=formGroup.get(x)
           if (gr.controls) //if has controls is a formGroup (or a FormArray)
                this.setEnabled(gr,value)
            else
            {
              console.log(gr.value) //<--show the value
              if (value)
                gr.enable()
              else
                gr.disable();
            }
         })
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      相关资源
      最近更新 更多