I am currently implementing the Reactive Forms Approach in my project. Within a form (with the parent component named: DeductionInvoicesComponent
), I have the following structure:
<form [formGroup]="deductionForm">
<div formArrayName="items" class="well well-lg">
<app-deduction-invoice-item
*ngFor="let item of deductionForm.get('items')?.controls; let i=index"
[index]="i"
(removed)="deductionForm.get('items').removeAt($event)">
</app-deduction-invoice-item>
</div>
</form>
<button type="button" class="btn btn-primary" (click)="addItem()">Add an item</button>
The TypeScript code for the parent component is as follows:
export class DeductionInvoicesComponent implements OnInit {
deductionForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.deductionForm = this.fb.group({
items: this.fb.array([])
});
}
addItem(){
let control = <FormArray>this.deductionForm.controls.items;
control.push(DeductionInvoiceItemComponent.buildItem());
}
}
This form can have multiple instances of DeductionInvoiceItemComponents
within a formArray
. The child component (a single item named: DeductionInvoiceItemComponent
) is structured as follows:
<div class="row" [formGroup]="item">
<div class="form-group col-4">
<label class="center-block">Title</label>
<select class="form-control" formControlName="title">
<option value="test">test</option>
</select>
</div>
<div class="form-group col-4">
<label class="center-block">Invoice Number</label>
<input class="form-control" formControlName="invoiceNumber">
</div>
<button (click)="removed.emit(index)" type="button" class="close text-danger" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
Furthermore, the TypeScript code for the single component representing an item in the formArray is as follows:
export class DeductionInvoiceItemComponent {
@Input()
public index: number;
@Input()
public item: FormGroup;
@Output()
public removed: EventEmitter<number> = new EventEmitter<number>();
static buildItem() {
return new FormGroup({
title: new FormControl('', Validators.required),
invoiceNumber: new FormControl('', Validators.required),
grossAmount: new FormControl('', Validators.required)
});
}
}
Upon clicking the addItem()
button, I encounter the following error message:
Error: formGroup expects a FormGroup instance
I am creating the FormGroup using the static buildItem
function as shown. How can I resolve this error?