我试图围绕使用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>
然后在我的打字稿中,我会有以下几点:
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,如果是这样的话怎么样?缺少有关如何对此表单的所有实例使用这些表单控件的链接。非常感谢任何帮助。
答案 0 :(得分:2)
您希望使用的是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>
以下是指向full example setup
的链接