I failed to get an Angular 2 reactive form to work which has a FormGroup nested in a FormArray. Can somebody show me what is wrong in my setup.
Unrelated parts of the code has been omitted for the brevity.
Following is my component
orderForm: FormGroup = this.fb.group({
id: [''],
store: ['', Validators.required],
//The part related to the error
order_lines: this.fb.array([
this.fb.group({
id: [''],
order_id: [],
product_id: [],
description: ['', Validators.required],
unit_price: ['', Validators.required],
discount: [0],
units: [1, Validators.required],
line_total: ['', Validators.required]
})
])
});
constructor(private fb: FormBuilder) { }
//Order instance is passed from elsewhere in the code
select(order: Order): void {
this.orderForm.reset(order)
}
The Order
instance passed to the select method is like this:
{
"id": 20,
"store": "Some Store",
"order_lines": [
{
"id": 6,
"order_id": 20,
"product_id": 1,
"description": "TU001: Polka dots",
"unit_price": "1000.00",
"discount": "100.00",
"units": 2,
"line_total": "1900.00"
},
{
"id": 7,
"order_id": 20,
"product_id": 2,
"description": "TU002: Polka dots",
"unit_price": "500.00",
"discount": "0.00",
"units": 1,
"line_total": "500.00"
}
]
}
The view template is like below.
<form [formGroup]="orderForm">
<input type="number" formControlName="id">
<input type="text" formControlName="store">
<div formArrayName="order_lines">
<div *ngFor="let line of orderForm.get('order_lines'); let i=index">
<div [formGroupName]="i">
<input type="text" [formControlName]="product_id">
<input type="text" [formControlName]="description">
<input type="number" [formControlName]="units">
<input type="number" [formControlName]="unit_price">
<input type="number" [formControlName]="line_total">
</div>
</div>
</div>
</form>
This setup gives me a console error **Cannot find control at order_lines -> 0 -> **. I'm wondering what I'm doing wrong.
I could get this to work with a simple FormControl inside the order_lines FormArray. But it fails with the given error when a FormGroup is used inside the FormArray.
Can you please help me to get this working.