【发布时间】:2023-03-14 14:03:01
【问题描述】:
我有一个formarray。如果我使用表单构建器对其进行初始化并推动它,它似乎可以正常工作。如果我采用与从中推送项目相同的数组,并尝试使用展开运算符一次将其全部添加,我会收到错误“错误错误:找不到路径的控件:'sizesArray -> 0'”
我的问题是,按照 ngrx/rsjx/功能响应式编程的精神,我怎样才能保持 Formarray '不可变'并从 FormGroup[] 分配给它,而不是清除、循环和推送?
以下是相关代码:
sizesArray: FormArray;
sizesArray2: FormArray;
sizes: Observable;
constructor(
private productStore: Store,
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
});
}
还有我的模板:
...
...
谢谢!
-
你不能对像 formGroup 这样复杂的对象使用扩展运算符,(扩展运算符给出“属性”的副本而不是方法,是的,你有,例如“属性”setValue,但不是一个“方法” setValue)。注意:我认为如果你使用 this.fb.array(sizes) 它必须是工作
-
@eliseo - 好点。我打算引入 lodash 的 cloneDeep 来解决它。谢谢!