javascript - 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>
如果您直接点击“其他表单”,它会正确显示其他表单,但如果您先点击“首先单击此处”或任何其他输入,则会出错:
错误错误:找不到名称为“测试”的控件
如果有人知道如何使它正常工作,它将使我免于数小时的挫败感。
解决方案
你可以更换
<div *ngIf="otherFormVisible">
和
<div [hidden]="!otherFormVisible">
推荐阅读
- python - 如何使用 pandas 将度分秒 (DMS) 数据直接从 .CSV 文件读取到数据帧中作为字符串?
- msbuild - 有没有办法通过 github 托管的运行器在 github 操作中使用 MSBuild 版本 12?
- javascript - Javascript使用反引号语法添加换行符
- flowable - 如何将表单中选择的字符串标识符分配给Flowable 3.6.1中的子流程?
- python - 功能问题
- javascript - 如何使按钮内的图标像按钮一样工作(指针事件:无;不起作用)
- xamarin.forms - 主详情页面加载菜单条目 MVVM
- apache-flink - Flink Process Function 没有将数据返回到 Sideoutputstream
- azure-logic-apps - Azure 存储队列和托管标识
- javascript - 如何使用 Javascript 连接到 Jitsi Videobridge