【发布时间】:2018-08-01 16:13:11
【问题描述】:
我正试图围绕使用 Angular 4 FormGroup 和 FormBuilder 的最佳方式展开思考。我现在正在使用一些虚拟 json 数据,例如:
bins = [
{
id: '101-Test',
system: 'test-system',
shape: 'round'
},
id: '102-Test',
system: 'test-system',
shape: 'round'
]
我打算做的是有一个 UI 显示可以编辑的“bins”行,还可以添加一个新的 bin。所以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 的值,然后将新的表单值推送到我的虚拟数据数组中。我如何也使用此表单组/控件来设置*ngFor 中编辑表单的值。我应该以某种方式从 Angular 实现 patchValue 吗?如果是这样,如何实现?缺少有关如何将这些表单控件用于此表单的所有实例的链接。非常感谢任何帮助。
【问题讨论】:
标签: javascript angular typescript angular-reactive-forms angular-forms