I've got an Angular component which displays data from a FormArray but there is also another FormGroup which only becomes visible when a button is clicked.
When the component loads, if I click on the button to make the other form visible immediately then it works. However if I click on another button or one of the FormArray inputs first when I make the other form visible it will error with 'Cannot find control'. Clicking to close and then re-display the other form will then work correctly.
I've spent hours trying to track down what's going wrong and it only seems to be when there is an *ngFor to loop through the FormArray items. I've boiled it down to this example:
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>
If you click straight on 'other form' it shows the other form correctly, but if you click on 'Click here first' or any of the other inputs first it will error saying:
ERROR Error: Cannot find control with name: 'test'
If anyone knows how to get this working properly it would save me from hours more frustration.
anotherClick()
implementation code. Could you please provide – Sats