类型 AbstractControl 不可分配给类型 FormGroup

Type AbstractControl is not assignable to type FormGroup

我有一个 FormGroup,其中 FormArray 控件充满了 FormGroup 个实例

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

另外,我有一个 getter 这个数组

  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.

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

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

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

模板:

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

组件:

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

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

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

在这里,这就是我解决问题的方法。当您还必须将 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[];
    }

这里我 return 来自 getter 的控件作为 FormGroup[]