首页 > 解决方案 > 如何引用 FormArray 的各个控件

问题描述

我被困在我需要在我的反应形式中用作我的数组的 formControlName 的内容上,我希望数组为 [1,2,3] 但我希望能够从数组中添加和删除,但也有多个数组,如果我创建新数组并从表单外部设置数组,我可以让它工作,但我觉得如果我制作一个大表单,它的扩展能力就不是很大,谢谢你的帮助

我已经厌倦了制作 formControlName="{{j}}" 并且当我控制台记录数组时我仍然得到一个空值

this.multiplerForm = this.fb.group({
  multipliers: this.fb.array([
    this.fb.group({
      reps: this.fb.array([]),
    })
  ])
});

addReps(control){
    control.push((this.fb.control('')));
}

removeReps(control,index: number) {
    control.removeAt(index);
}
<StackLayout formArrayName="reps">
    <GridLayout rows="*" columns="*,*,*" *ngFor="let rep of multiplier.get('reps').controls;  let j=index" [formGroupName]="j"  >
        <Label col="0" text="Set {{j+1}}" ></Label>
        <TextField col="1" formControlName="{{j}}" ></TextField>
        <Button col="2" text="X" (tap)="removeReps(multiplier.controls.reps,j)"></Button>
    </GridLayout>
</StackLayout>

标签: angularnativescript

解决方案


Darian FormArray 可以是 FormGroups 的 FormArray 或 FormControls 的 FormArrays。你有一个 FormControls 的 Formarray,所以你使用 [formControlName]="i",而不是 [formGroupName]="i"

<div *ngFor="let rep of multiplier.get('reps').controls; let i=index">
    <label>
      Alias:
      <input type="text" [formControlName]="i">
    </label>
  </div>

推荐阅读