Angular Reactive Form - Form Array - 如何使用扩展运算符设置 FormArray?

Angular Reactive Form - Form Array - How do I set FormArray with spread operator?

我有一个表格。如果我用 formbuilder 初始化它并推入它,它似乎工作正常。如果我使用我从中推送项目的同一个数组,并尝试使用扩展运算符一次添加它,我会收到错误 "ERROR Error: Cannot find control with path: 'sizesArray -> 0'"

我的问题是,为了与 ngrx/rsjx/functional-reactive 编程的精神保持一致,我怎样才能保留 Formarray 'immutable' 并从 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([])。然后,在订阅者的下一个回调中,您将更改引用。这个值也是'captured' by formControlName='sizesArray',也就是说

<div *ngFor="let size of sizesArray.controls; let i = index;" [formGroupName]="i">

会创建多个FormGroup个实例,它们是children的一个容器sizesArray,它是空的。

现在,this.sizesArray(您在模板中对其进行迭代)指向其他内容,即:this.fb.array([...sizes]).

所以,基本上发生的是 sizesArraysizeForm 的 child)指向一个空的 FormArraythis.sizesArray 指向一个 non-empty FormArray.

在这种情况下你可以做的是:

.subscribe(sizes => {
  this.sizeForm.setControl('sizeArray', this.fb.array(sizes))
})