How to iterate formgroup with array in Angular2
Fixed it!!!
So apparently I need to read up on Angular2 Fundamentals because I thought my mistake was legal. Basically, I ignored the square brackets around formGroupName in the tutorial because I've done it numerous times before without issue, but not this time. So to fix I simply added the brackets:
<div formGroupName="i"> => <div [formGroupName]="i">
Here is the solution that worked for me. https://plnkr.co/edit/cs244r
HTML Template:
<div>
<h2>RegionId: {{regionId}}</h2>
<h2>Region: {{region.name}}</h2>
</div>
<form [formGroup]="regionFormGroup">
Region Name: <input type="text" formControlName="regionName" [(ngModel)]="region.name" />
<div formArrayName="customersArray">
<table class="simple-table">
<tr>
<th>Customer</th>
<th>Current Period</th>
<th>Previous Period</th>
</tr>
<tbody>
<tr [formGroupName]="i" *ngFor="let customerGroup of regionFormGroup.controls.customersArray.controls; let i = index">
<td>{{region.customers[i].name}} - index {{i}}</td>
<td><input type="text" formControlName="currentPeriod" [(ngModel)]="region.customers[i].currentPeriod"/></td>
<td><input type="text" formControlName="previousPeriod" [(ngModel)]="region.customers[i].previousPeriod"></td>
</tr>
</tbody>
</table>
</div> <!-- end: div FormArrayName -->
</form>
Component.ts
export class AppComponent implements OnInit {
regionId: number = 5;
region: RegionModel;
regionFormGroup: FormGroup;
constructor( private customerService: CustomerService,private fb: FormBuilder) { }
ngOnInit(): void {
// initialize form
this.regionFormGroup = new FormGroup({
regionName: new FormControl(''),
customersArray: new FormArray([])
});
// Retrieve data from datasource
this.customerService.getCustomerByRegion(5)
.subscribe( (reg: RegionModel ) => {
this.region = reg;
this.buildForm();
});
}
buildForm = () : void => {
const customersControls = <FormArray>this.regionFormGroup.controls['customersArray'];
this.region.customers.forEach( (cust : CustomerModel) => {
customersControls.push(this.createCustomerFormGroup(cust));
console.log(customersControls);
});
}
createCustomerFormGroup(cust: CustomerModel) {
return this.fb.group({
currentPeriod: [''],
previousPeriod: ['']
});
}
}