【发布时间】:2018-12-21 20:00:49
【问题描述】:
我正在尝试创建一个输入表单,其中输入的标签和 FormControl 名称来自模型中定义的对象数组,而不是从用户操作动态生成每个新输入。我看到的所有示例都是针对用户单击按钮添加新输入的场景,但我的用例没有看到任何示例。
我曾尝试使用官方 Angular 指南 here 中的示例以及我在其他地方搜索时发现的许多示例,但我无法弄清楚如何将信息正确推送到 FormArray 上。标签被正确填充并且输入的数量正确,但是模型和视图之间的绑定没有发生。这是我得到的最接近的:
打字稿:
import { FormGroup, FormControl, FormBuilder, FormArray, Validators } from '@angular/forms';
export class LabFormComponent implements OnInit {
specimenControls: FormArray;
constructor(
private router: Router,
private formBuilder: FormBuilder
) { }
async ngOnInit() {
await this.addSpecimens();
}
specimens = [
{ label: "SST: ", name: "sst" },
{ label: "LAV: ", name: "lav" },
{ label: "BLUE: ", name: "blue"}
];
specimenFields : FormGroup = this.formBuilder.group({
specimenControls: this.formBuilder.array([
])
});
addNewFormControl(specimen) {
const control = <FormArray>this.specimenFields.controls['specimenControls'];
control.push(this.formBuilder.control(specimen));
}
addSpecimens() {
for(let specimen of this.specimens) {
this.addNewFormControl(specimen);
}
}
HTML:
<div>
<form [formGroup]="specimenFields" (ngSubmit)="addSpecs();showSpecForm=false">
<div formArrayName="specimenControls">
<div *ngFor="let specimen of specimens; let i=index" style="margin-bottom:10px">
<label class="form-label">{{specimen.label}}</label>
<input matInput class="form-textbox" type="text" [formControlName]="i" maxlength="2" size="2" value="0"/>
<button mat-raised-button style="margin-left:15px;" (click)="decNumber(this.value)" color="primary">-</button>
<button mat-raised-button style="margin-left:10px;" (click)="incNumber(this.value)" color="primary">+</button>
</div>
</div>
<button mat-raised-button type="submit" color="primary">Submit</button>
</form>
</div>
我希望每个动态生成的输入都具有双向绑定,但我得到了以下错误:
"Cannot find control with path: 'specimenControls -> 0'"
我到处查看这个错误,但正如我之前提到的,我看到的所有场景都是针对用户单击按钮添加新输入的情况。如果我在 addNewFormControl() 方法中使用console.log(control),我可以看到 FormControl 对象,所以我知道“某事”正在发生,但我不知道为什么它没有看到它。例如:
{…}
_onCollectionChange: function _onCollectionChange()
_onDisabledChange: Array []
_parent: Object { pristine: true, touched: false, status: "VALID", … }
asyncValidator: null
controls: (3) […]
0: {…}
_onChange: Array []
_onCollectionChange: function _onCollectionChange()
_onDisabledChange: Array []
_parent: Object { pristine: true, touched: false, status: "VALID", … }
_pendingValue: Object { label: "SST: ", name: "sst" }
asyncValidator: null
errors: null
pristine: true
status: "VALID"
statusChanges: Object { _isScalar: false, closed: false, isStopped: false, … }
touched: false
validator: null
value: Object { label: "SST: ", name: "sst" }
【问题讨论】:
标签: angular angular-reactive-forms