簡體   English   中英

Angular FormArray 導致另一種形式的 Formcontrol 丟失

[英]Angular FormArray causing Formcontrol in another form to be lost

我有一個 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>

如果您直接單擊“其他表單”,它會正確顯示其他表單,但如果您先單擊“首先單擊此處”或任何其他輸入,則會出現錯誤提示:

ERROR 錯誤:找不到名稱為“test”的控件

如果有人知道如何使其正常工作,它將使我免於數小時的沮喪。

你可以更換

<div *ngIf="otherFormVisible">

<div [hidden]="!otherFormVisible">

同意@Stratubas 的回答並感謝他指出問題。

此問題在chrome version is 79.0.3945.130 (官方chrome version is 79.0.3945.130 )(64 位)中無法重現。

但是我在 Microsoft Edge 中 @PierreDuc 提供的 stackblitz 鏈接中嘗試了相同的問題,該鏈接的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM