使用 Angular 4 表单组编辑和添加新数据

Using Angular 4 Form Group for Editing and Adding new data

我正在努力思考使用 Angular 4 FormGroup 和 FormBuilder 的最佳方式。我现在有一些虚拟 json 数据,例如:

bins = [ 
 {
   id: '101-Test',
   system: 'test-system',
   shape: 'round'
 },
   id: '102-Test',
   system: 'test-system',
   shape: 'round'
]

我打算做的是有一个 UI,它将显示 'bins' 行,可以编辑这些行,还可以添加新的垃圾箱。所以 html/ngFor/ngIf's 看起来像这样:

<div id="bins">
   <div class=bin-card new" *ngIf="addBinCardVisible">
      <form [formGroup]="binSetupForm">
          <label>Bin # <input type="text" formControlName="id"></label>
          <label>Bin # <input type="text" formControlName="system"></label>
          <label>Bin # <input type="text" formControlName="shape"></label>
      </form>
   </div>
   <div class="bin-card-wrap" *ngFor="let bin of bins; let i = index">
      <form [formGroup]="binSetupForm">
         <label>Bin # <input type="text" formControlName="id"></label>
          <label>Bin # <input type="text" formControlName="system"></label>
          <label>Bin # <input type="text" formControlName="shape"></label>
      </form>
   </div>
</div>

然后在我的 Typescript 中,我会有一些类似的东西:

export class BinSetupComponent implements OnInit {

   addBinCardVisible = false;

   binSetupForm: FormGroup;

   constructor(private formBuilder: FormBuilder) { }

   ngOnInit() {
      this.buildForm();
   }

   buildForm(): void {
     this.binSetupForm = this.formBuilder.group({
        id: '',
        system: '',
        shape: ''
     });
   }

   addNewBin() {
      this.bins.splice(0, 0, this.binSetupForm.value);
      this.addBinCardVisible = false;
      this.binSetupForm.reset();
   }  
}

如您所见,我正在使用 Angular Form Builder 来构建 binSetupForm 的值,然后将新的表单值推送到我的虚拟数据数组中。我还如何使用此表单 Group/Controls 来设置 *ngFor 中编辑表单的值。我应该以某种方式从 Angular 实施 patchValue 吗?如果是的话,如何实施?缺少有关如何将这些表单控件用于此表单的所有实例的 link。非常感谢任何帮助。

您希望使用的是 FormArray,您将像这样设置您的表单

this.binsForm = new FormGroup({
    bins: new FormArray([
        new FormGroup({
            id: new FormControl('101-Test'),
            system: new FormControl('test-system'),
            shape: new FormControl('round')
        }),
        new FormGroup({
            id: new FormControl('102-Test'),
            system: new FormControl('test-system'),
            shape: new FormControl('round')
        })
    ]
});

在你的 *.component.html 文件中

<div [formGroup]="binsForm">
    <div formArrayName="bins">
      <div *ngFor="let bin of bins; let i = index">
        <div [formGroupName]="i">
            <input type="text" formControlName="id" />
            <input type="text" formControlName="system" />
            <input type="text" formControlName="shape" />
        </div>
      </div>
    </div>
</div>

这是一个link到一个full example setup