首页 > 解决方案 > Angular FormArray 导致另一种形式的 Formcontrol 丢失

问题描述

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

当组件加载时,如果我单击按钮使另一个表单立即可见,那么它就可以工作。但是,如果我在使另一个表单可见时首先单击另一个按钮或一个 FormArray 输入,则会出现“找不到控件”错误。单击以关闭然后重新显示另一个表单将正常工作。

我花了几个小时试图找出出了什么问题,而且似乎只有当有一个 *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>

如果您直接点击“其他表单”,它会正确显示其他表单,但如果您先点击“首先单击此处”或任何其他输入,则会出错:

错误错误:找不到名称为“测试”的控件

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

标签: javascriptangularangular-forms

解决方案


你可以更换

<div *ngIf="otherFormVisible">

<div [hidden]="!otherFormVisible">

推荐阅读