I have a form that's initialized in the component's constructor:
constructor(
private fb: FormBuilder,
) {
this.form = this.fb.group({
practice: [''],
jobs: this.fb.array([
this.fb.group({
name: ['', [Validators.required]],
dateRange: [{startDate: null, endDate: null}, [Validators.required]],
}),
]),
});
}
And it's value is set like this:
@Input() set profile(newValue: Partial<FormModel>) {
this.form.patchValue(newValue);
if (value?.jobs.length) {
this.form.setControl('jobs', this.fb.array(newValue.jobs));
}
}
If newValue has more than one element in 'jobs', patchValue sets only one of them, because only one element is declared in constructor. That's why I also added setControl, and it seems to work fine - when I output this.form.value, it's value is identical to newValue. BUT I have troubles with displaying it in the template. That's how my html looks like:
<nz-form-control formArrayName="jobs">
<ng-container
*ngFor="let job of form.get('jobs').controls; let i=index"
[formGroupName]="i"
>
<input formControlName="name"/>
<app-range-datepicker
formControlName="dateRange"
></app-range-datepicker>
</ng-container>
</nz-form-control>
And I get errors in the console for every control (in case of 2 jobs):
Cannot find control with path: 'jobs -> 0 -> name'
Cannot find control with path: 'jobs -> 0 -> dateRange'
Cannot find control with path: 'jobs -> 1 -> name'
Cannot find control with path: 'jobs -> 1 -> dateRange'
(at setUpControl, at FormGroupDirective.addControl)