I am trying to wrap my head around the best way to use Angular 4 FormGroup and FormBuilder. I have some dummy json data that I am working with for now such as this:
bins = [
{
id: '101-Test',
system: 'test-system',
shape: 'round'
},
id: '102-Test',
system: 'test-system',
shape: 'round'
]
What I intend to do is have a UI that will show rows of 'bins' which can be edited but also the ability to add a new bin. So the html/ngFor/ngIf's would look like this:
<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>
And then in my Typescript I would have something along the lines of:
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();
}
}
As you can see I am using Angular Form Builder to build the values of the binSetupForm and then pushing the new form value into my dummy array of data. How do I also use this Form Group/Controls to set the values of the edit forms in the *ngFor. Should I somehow be implementing patchValue from Angular and if so how? Missing the link on how to use these form controls for all instances of this form. Any help is much appreciated.