【发布时间】:2020-05-24 23:19:54
【问题描述】:
我有一个 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>
如果您直接点击“其他表单”,它会正确显示其他表单,但如果您先点击“首先点击此处”或任何其他输入,则会出错:
错误错误:找不到名称为“test”的控件
如果有人知道如何让它正常工作,那会让我摆脱更多的挫败感。
【问题讨论】:
-
无法重现您的 Typescript 代码给出的问题。我猜您缺少
anotherClick()实现代码。能否请您提供
标签: javascript angular angular-forms