Angular FormArray导致另一个窗体中的Formcontrol丢失

Angular FormArray causing Formcontrol in another form to be lost

我有一个 Angular 组件显示来自 FormArray 的数据,但还有另一个 FormGroup 只有在单击按钮时才可见。

加载组件时,如果我单击按钮使另一个表单立即可见,那么它就可以工作了。但是,如果我在使另一个表单可见时首先单击另一个按钮或其中一个 FormArray 输入,则会出现 'Cannot find control' 错误。单击以关闭然后重新显示其他表单将正常工作。

我花了几个小时试图找出问题所在,但似乎只有在有 *ngFor 循环遍历 FormArray 项时才会出现问题。我把它归结为这个例子:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'app-test-filter-component',
  templateUrl: './test-filter-component.component.html',
  styleUrls: ['./test-filter-component.component.scss']
})
export class TestFilterComponentComponent implements OnInit {

  public testform: FormGroup;
  public otherForm: FormGroup;
  public otherFormVisible = false;

  constructor() {}

  get orders() {
    return this.testform.get('orders') as FormArray;
  }

  anotherClick() {}

  ngOnInit() {
    this.testform = new FormGroup({
      orders: new FormArray([])
    });
    this.otherForm = new FormGroup({
      test: new FormControl('testvalue')
    });
    for(let idx = 0; idx < 50; idx++) {
      this.orders.push(new FormGroup({id: new FormControl(idx), name: new FormControl('test')}));
    }
  }
}
<div *ngIf="otherFormVisible">
    <form [formGroup]="otherForm">
        <input formControlName="test">
    </form>
</div>
<button class="btn btn-primary" (click)="otherFormVisible = !otherFormVisible">other form</button>
<button class="btn btn-primary" (click)="anotherClick()">Click here first</button>
<form [formGroup]="testform">
    TEST CONTROL
    <div formArrayName="orders" *ngFor="let order of orders.controls; let i = index">
        <div [formGroupName]="i">
            <input formControlName="id">
            <input formControlName="name">
        </div>
    </div>
</form>

如果您直接点击 'other form',它会正确显示其他表格,但如果您先点击 'Click here first' 或任何其他输入,它将出错:

ERROR Error: Cannot find control with name: 'test'

如果有人知道如何使它正常工作,它将使我免于数小时的挫败感。

你可以替换

<div *ngIf="otherFormVisible">

<div [hidden]="!otherFormVisible">

同意@Stratubas 的回答并感谢他指出问题。

此问题在 chrome version is 79.0.3945.130(官方构建)(64 位)中无法重现。

但我在 Microsoft Edge 中尝试了@PierreDuc 在 stackblitz link 中提出的相同问题,该问题具有 Version 80.0.361.48(官方版本)(64 位),此问题可在此处重现。该浏览器是微软基于 Chromium 的浏览器。

我希望这对以后的任何人都有帮助。

虽然接受的答案确实解决了我发布的小示例,但当我的表单变得更复杂时,问题很快又出现了。

经过进一步搜索,我发现它实际上是 Chrome 80+ 的错误 https://github.com/angular/angular/issues/35214

这里有一个解决方法可以解决我的问题: https://github.com/angular/angular/issues/35219#issuecomment-583425191