类型“AbstractControl | null' 不可分配给类型 'NgIterable<any> | 空 | 不明确的'

Mun*_*san 1 angular angular-reactive-forms

我的 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');
  }
Run Code Online (Sandbox Code Playgroud)

.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>
Run Code Online (Sandbox Code Playgroud)

我试图找到并解决问题,但没有提供解决方案或答案。

yur*_*zui 5

您需要迭代控件,但要传递一个实例AbstractControl或可能的null值来ngFor循环。

我猜你想在你的FormArray.

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

get refForm() {
  return this.forms.get('topics') as FormArray;
                                  ^^^^^^^^^^^^
}
Run Code Online (Sandbox Code Playgroud)

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

*ngFor="let topic of refForm.controls"
Run Code Online (Sandbox Code Playgroud)