类型 'AbstractControl | null' 不可分配给类型 'NgIterable<any> | null | undefined'

Type 'AbstractControl | null' is not assignable to type 'NgIterable<any> | null | undefined'

我的component.ts代码是

forms = new FormGroup({
    topics: new FormArray([]),
  });

  addTopic(topic: HTMLInputElement) {
    (this.refForm as FormArray).push(new FormControl(topic.value));
    // topic.value = '';
  }

  get refForm() {
    return this.forms.get('topics');
  }

和 .html 文件具有以下代码。

<form [formGroup]="forms">
  <input
    type="text"
    class="form-control"
    (keyup.enter)="addTopic(topic)"
    #topic
  />
  <ul class="list-group">
    <li *ngFor="let topic of forms.get('topics')">
      class="list-group-item">
      {{ topic.value }}
    </li>
  </ul>
</form>

我试图找到并解决问题,但没有可用的解决方案或答案。

您需要迭代控件,但您正在将 AbstractControl 或可能的 null 值的实例传递给 ngFor 循环。

我猜您想在 FormArray.

中传递控件数组

您已经有一个可以通过正确类型得到增强的 get 助手:

get refForm() {
  return this.forms.get('topics') as FormArray;
                                  ^^^^^^^^^^^^
}

使用上面的代码你可以更正你的 html

*ngFor="let topic of refForm.controls"