【问题标题】:Working with form elements in child component raises formControlName error在子组件中使用表单元素会引发 formControlName 错误
【发布时间】:2018-01-01 05:53:25
【问题描述】:

各位,节日快乐,

请耐心等待,因为英语是我的第三语言。

我正在将一个 JQuery 驱动的应用程序移动到有角度的应用程序并卡住了。有不同的报告相关模块取决于日期,我想创建一个组件并导入到父组件。我的印象是调用子组件只是注入子组件模板中的任何内容,但我现在猜想(图片 php 的包含函数)。

The plunkr 显示了我尝试过的基本安排。但基本上,我想在其他父组件中使用日期组件。例如在我的父组件中,我有这个:

        this.rForm = fb.group({
     'processedon': fb.group ({
        'datefilteroption' : [null, [Validators.required]],
        'dateportion' : [null, []],
        'date1': [null, []],
        'date2': [null, []]
      })
     });

其中,处理下的子元素是在我的子表单中定义的元素。子组件 hmtl 模板包含与它们匹配的 formControlName(date1、date2 等)。我可以在同一输出中有更多日期要求,因此可以将上述内容扩展如下。这个想法是子组件保持不变,该组将用于从几乎任何地方操作其组件。

   this.rForm = fb.group({
     'processedon': fb.group ({
        'datefilteroption' : [null, [Validators.required]],
        'dateportion' : [null, []],
        'date1': [null, []],
        'date2': [null, []]
      }),
     'paidbackon': fb.group ({
        'datefilteroption' : [null, [Validators.required]],
        'dateportion' : [null, []],
        'date1': [null, []],
        'date2': [null, []]
      })
     });

我现在得到的错误是“使用子组件时,formControlName 必须与父 formGroup 指令一起使用”。我试图在子组件中创建一个 formGroup,但这迫使我在一个表单中创建一个表单并且是错误的。

我希望我的问题很清楚。

【问题讨论】:

    标签: angular


    【解决方案1】:

    解决您的问题的最简单方法是在您的子组件的viewProviders 数组中提供ControlContainer

    import { ControlContainer, FormGroupName  } from '@angular/forms';
    
    @Component({
      selector: 'app-date-query',
      templateUrl: './date-query.component.html',
      ...
      viewProviders: [
        { provide: ControlContainer, useExisting: FormGroupName  }
      ]
    })
    export class DateQueryComponent implements OnInit {
    

    Stackblitz Example

    另见

    【讨论】:

    • 谢谢@yurzui。错误至少消失了。让我玩一下并确认所有内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2017-03-30
    • 2021-02-19
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多