我有一个formarray。如果我使用formbuilder对其进行初始化并将其推入,它似乎可以正常工作。如果我要从中推送项目的数组相同,并尝试使用价差运算符一次将其全部添加,则会收到错误消息“错误错误:找不到路径为'sizesArray-> 0'的控件”
我的问题是,按照ngrx / rsjx / functional-active编程的精神,我如何才能使Formarray保持“不可变”并从FormGroup []分配给它,而不是清除,循环和推送?
以下是相关代码:
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
});
}
和我的模板:
...
<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>
...
谢谢!
我认为问题是,你改变的引用。
this.sizeForm = this.fb.group({
sizesArray: this.sizesArray
});
此时指向sizeArray
所引用的值this.sizesArray
,即this.fb.array([])
。然后,在订户的下一个回调中,您正在更改引用。此值也由捕获formControlName='sizesArray'
,表示
<div *ngFor="let size of sizesArray.controls; let i = index;" [formGroupName]="i">
将创建多个FormGroup
实例,这些实例是容器的子代,该容器sizesArray
为空。
现在,this.sizesArray
(您要在模板中对其进行迭代)指向其他内容,即:this.fb.array([...sizes])
。
因此,基本上发生的是sizesArray
(的孩子sizeForm
)指向一个空值,FormArray
并且this.sizesArray
指向一个非空值 FormArray
。
在这种情况下,您可以做的是:
.subscribe(sizes => {
this.sizeForm.setControl('sizeArray', this.fb.array(sizes))
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句