【问题标题】:Type 'AbstractControl | null' is not assignable to type 'NgIterable<any> | null | undefined'键入“抽象控件 | null' 不可分配给类型 'NgIterable<any> |空 |不明确的'
【发布时间】:2021-12-26 18:34:54
【问题描述】:

我的 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>

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

【问题讨论】:

    标签: angular reactive-forms


    【解决方案1】:

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

    我猜你想在FormArray 中传递一系列控件。

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

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

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

    *ngFor="let topic of refForm.controls"
    

    【讨论】:

    • 这段代码得到了这个错误类型'{ [key: string]: AbstractControl; }' 不可分配给类型 'NgIterable |空 |未定义'。
    • 请仔细查看我添加的所有代码。你加as FormArray了吗?
    • 是的。 get refForm() { return this.forms.get('topics') as FormArray; }
    • 请在这里测试我的代码stackblitz.com/edit/…
    • 它在这里工作。 stackblitz.com/edit/…
    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 2021-11-08
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多