【问题标题】:Angular Reactive Form: Using a FormArray and adjusting the FormControls leads to Error There is no form control element for pathAngular Reactive Form:使用 FormArray 并调整 FormControls 会导致错误路径没有表单控件元素
【发布时间】:2021-05-14 08:53:31
【问题描述】:

我正在创建一个可过滤的表。第一列包含用于选择行的复选框,最终用户可以对选择进行一些操作。

在过滤器上,我正在做:

public resetFormRows(items: any[]) {
    this.formGroup.removeControl('rows');
    const newRows = items.map(_ => new FormControl(false));
    const newFormArray = new FormArray(newRows);
    this.formGroup.addControl('rows', newFormArray);
}

过滤表格后,我可以 console.log 控件并看到 FormArray 包含新的 FormControl。但是,当我选中移动的行(即更改的行索引)的复选框时,会显示以下错误:

ERROR 错误:没有 FormControl 实例附加到表单控件 带有路径的元素:'rows -> 1'

这是一个演示该错误的堆栈闪电战: https://stackblitz.com/edit/angular-8-template-form-fzsyse?file=src%2Fapp%2Ftable.component.ts

要显示错误,请执行以下操作:

  • 选择过滤器复选框:“有所有者吗?”
  • 选中“订书机”复选框

我有几个问题:

  • 为什么会出现此错误,为什么我的 console.log 显示 FormControl 但错误提示我没有?
  • 错误堆栈跟踪没有指向我的代码库中的任何特定内容。那么,人们通常如何调试这些问题?

【问题讨论】:

  • 这很奇怪,如果你用 1 替换 i,它会起作用,我并不是说这是一个修复,我只是对这种行为感到好奇

标签: angular angular-reactive-forms


【解决方案1】:

不要使用 formControlName 指令,而是尝试使用 thread 中提到的 formControl 独立指令:

试试这个:

    <tr *ngFor="let item of filteredData$ | async; index as i">
        <td>
            <label><input type="checkbox" checkBoxDirective [formControl]="myForm.get('rows').controls[i]" /></label>
        </td>
        <td>
            {{ item.name }}     
        </td> 
    </tr>

Forked Example

【讨论】:

  • 谢谢!按预期工作
【解决方案2】:

您的表单数组包含表单控件,但它们没有任何名称,因此您无法使用 formControlName 访问它们

解决这个问题:

在ts中:

  get formArray() {
      return this.myForm.controls.rows as FormArray;
  }

在html中

<input type="checkbox" checkBoxDirective [formControl]="formArray.controls[i]" />

正在工作的 stackblitz 链接:

https://stackblitz.com/edit/angular-8-template-form-8xnmdp?file=src%2Fapp%2Ftable.component.html

【讨论】:

    猜你喜欢
    • 2021-06-04
    • 2020-10-02
    • 2021-05-02
    • 2020-09-30
    • 2018-07-15
    • 2021-09-09
    • 2023-03-07
    • 1970-01-01
    • 2018-10-28
    相关资源
    最近更新 更多