首页 > 解决方案 > Angular Forms,构建对象数组

问题描述

我正在尝试使用 Angular 表单构建一组对象,但我无法让它工作。

问题:如何使用 Angular 表单构建对象数组?

这是我想要的:

productForm = this.fb.group({
businessNotes: this.fb.array([
      [key: valuePair]
    ]),
});

这是我所拥有的:

component:

productForm = this.fb.group({
businessNotes: this.fb.array([
      this.fb.group({
        text: ['']
      })
    ]),
});

addBusinessNote() {
 let control = (<FormArray> (<FormGroup>this.productForm).get('businessNotes')).controls;
    control.push(this.fb.group({text: ['']}));
}

get businessNotes() {
return this.productForm.get('businessNotes') as FormArray;
}

html:
<div>
    <p>Business Notes:</p>
    <div formArrayName="businessNotes">
      <h3>business notes</h3> <button (click)="addBusinessNote()">Add business note</button>

      <div *ngFor="let note of productForm.controls.businessNotes.controls; let i=index ">
        <label>
          note: {{i + 1}}
          <input type="text" [formControlName]="text">
        </label>
      </div>
    </div>
  </div>

这是我得到的输出:

ProductAddComponent.html:69 ERROR Error: Cannot find control with path: 'businessNotes -> '
    at _throwError (forms.js:2144)
    at setUpControl (forms.js:2052)
    at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:5281)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:5882)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:5803)
    at checkAndUpdateDirectiveInline (core.js:22085)
    at checkAndUpdateNodeInline (core.js:23353)
    at checkAndUpdateNode (core.js:23315)
    at debugCheckAndUpdateNode (core.js:23949)
    at debugCheckDirectivesFn (core.js:23909)

标签: angularangular-forms

解决方案


这里有一个很好的简短解释,例如: https ://alligator.io/angular/reactive-forms-formarray-dynamic-fields/


推荐阅读