我正在尝试使用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)
答案 0 :(得分:0)
答案 1 :(得分:0)
尝试一下:
<div formArrayName="businessNotes">
<h3>business notes</h3> <button (click)="addBusinessNote()">Add business note</button>
<div *ngFor="let note of businessNotes.controls; let i=index" >
<label>
note: {{i + 1}}
<input type="text" [formControl]="note.get('text')">
</label>
</div>
</div>
</div>
我认为它对[formControlName] =“ text”部分最不高兴。它不确定是哪个形式的组。我认为可以通过多种方式解决此问题,但是我发现绑定到formControl是最棘手的问题。
我认为您的add方法中也可能存在错误。我认为您不需要这里的array.controls,您可以直接将其推入数组。
祝你好运!