【问题标题】:Type AbstractControl is not assignable to type FormGroup类型 AbstractControl 不可分配给类型 FormGroup
【发布时间】:2022-05-09 15:39:10
【问题描述】:

我有一个带有FormArrayFormGroup 控件,其中填充了FormGroup 实例

  someForm = this.fb.group({
    days: this.fb.array([
      this.fb.group({
        description: ['']
      })
    ])
  })

另外,我有这个数组的吸气剂

  get days(): FormArray {
    return this.someForm.get('days') as FormArray;
  }

当我尝试遍历FormArray 并将其分配给[formGroup] 指令时,如this article 中所示

 <div *ngFor="let day of days.controls">
  <ng-container [formGroup]="day">
    ...

我来了

error TS2740: Type 'AbstractControl' is missing the following properties from type 'FormGroup': controls, registerControl, addControl, removeControl, and 3 more.

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

    我在this article 中找到了一种解决方法,通过index 遍历FormGroups,例如:

     <div *ngFor="let day of days.controls; let i=index">
          <ng-container [formGroupName]="i">
             ...
    
    

    【讨论】:

    • 是的,这是正确的解决方案。顺便提一句。 *ngFor="let day of days.controls" 实际上 工作(我认为 Angular 9 不允许这样做-检查文章何时写作-)
    【解决方案2】:

    另一种解决方法是在组件中使用强制转换。

    模板:

    <ng-container [formGroup]="getFormGroup(day)">
    

    组件:

    getFormGroup(control: AbstractControl) { return control as FormGroup; }
     
    

    这样我们仍然可以将控件用作在 ngFor for formArray 中循环的组件的输入值

    <ng-container *ngFor="let day of days.controls">
        <childComponent [formGroup]="day"></childComponent>
    </ng-container>
    

    【讨论】:

      【解决方案3】:

      在这里,这就是我解决问题的方法。当您必须将 formGroup 也传递给子组件时,这种方法很有用

      模板:

      <ng-container formArrayName="days" *ngFor="let day of days;>
        <form [formGroup]="day"></form>
      </ng-container>
      

      组件:

        get days(): FormGroup[] {
             const formArray = this.someForm?.get('days') as FormArray;
             return formArray.controls as FormGroup[];
          }
      

      这里我将 getter 中的控件返回为 FormGroup[]

      【讨论】:

      • 从 Angular 9 你应该使用&lt;div *ngFor="let day of days.controls;let i=index"&gt;&lt;ng-container [formGroupName]="i"&gt;...&lt;/bg-container&gt;&lt;/div&gt;。看到使用[formGroupName]和变量的索引
      • 嗨@Eliseo,谢谢。我使用这种方法是因为我必须将 formGroup 实例传递给子表单字段组件。我在 Angular 13 上,最近开始学习 Angular。
      • 如果你有一个子组件,你的方法真的没问题。好吧,我更喜欢使用“像 getter 一样的输入,请参阅例如这个 SO 或使用 { provide: ControlContainer, useExisting: FormGroupDirective }, 像这样另一个 SO
      猜你喜欢
      • 1970-01-01
      • 2021-06-08
      • 2018-04-15
      • 2021-08-22
      • 2020-06-02
      • 2016-11-21
      • 2020-05-12
      • 1970-01-01
      • 2020-04-02
      相关资源
      最近更新 更多