I've got a formarray. If I initialize it with a formbuilder and push onto it, it seems to work okay. If I take the same array that I'm pushing items from, and try to add it all at once with the spread operator, I get the error "ERROR Error: Cannot find control with path: 'sizesArray -> 0'"
My question is, in keeping with the spirit of ngrx/rsjx/functional-reactive programming, how can I keep the Formarray 'immutable' and assign to it from the FormGroup[] rather than clearing, looping and pushing?
Here's the relevant code:
sizesArray: FormArray;
sizesArray2: FormArray;
sizes: Observable<SizeModel[]>;
constructor(
private productStore: Store<productState.State>,
private fb: FormBuilder
) {
this.sizes = productStore.select(productState.selectSizes);
}
ngOnInit() {
this.sizesArray = this.fb.array([]);
this.sizesArray2 = this.fb.array([]);
this.sizes
.pipe(
skipWhile(sizes => !sizes),
map(sizes => {
return sizes.map(size => this.fb.group({size}));
}
)
)
.subscribe(
sizes => {
// this is the code I want to use. that throws the error
this.sizesArray = this.fb.array([...sizes]);
// this code works, but I don't know how it's different than the code above
this.sizesArray2.clear();
sizes.forEach( size => {
this.sizesArray2.push(size);
});
}
);
this.sizeForm = this.fb.group({
sizesArray: this.sizesArray
});
}
and my template:
...
<form [formGroup]="sizeForm">
<fieldset id="size-container">
<legend>Sizes</legend>
<div formArrayName="sizesArray" >
<div *ngFor="let size of sizesArray.controls; let i = index;" [formGroupName]="i">
<app-size-form
formControlName="size"
(deleteClicked)="deleteSize(i);">
</app-size-form>
</div>
</div>
</fieldset>
<button (click)="addSize()" id="size-button">Add Size</button>
<button mat-button matStepperPrevious>Back</button>
<button mat-button (click)="submit()">Save</button>
</form>
...
Thanks!