I am trying to build a nested reactive form in Angular 5. I am able to push items at one level, but unable to push item at second level.
ngOnInit() {
this.
So first let start with understanding what you do.
You make a formarray in formarray. So this mean it have two loops. So you have to *ngFor the first and *ngFor the second. In the end this means you have an index i for your items and and j for your subItems. Then you can add addSubItems(i)
for pushing your subItems.
Your html should look something like this:
<form [formGroup]="orderForm">
<div formArrayName="items">
<div *ngFor="let arrays of orderForm.controls.items.controls; let i = index;">
<div formGroupName="{{i}}">
<input formControlName="name" placeholder="Item name">
<input formControlName="description" placeholder="Item description">
<input formControlName="price" placeholder="Item price">
<input type="button" value="subAdd" (click)="addSubItems(i)"> <-- here your button -->
<div formArrayName="subItems">
<div *ngFor="let item of arrays.controls.subItems.controls; let j = index;">
<div formGroupName="{{j}}">
<input formControlName="subname" placeholder="Item subname">
Your addSubItems should look something like:
addSubItems(_index: any): void {
this.item = this.orderForm['controls']['items']['controls'][_index] as FormGroup;
this.subItems = this.item.get('subItems') as FormArray;
this.subItems.push(this.createSubItem());
To reduce amount of code, these can little refactored addSubItems(index) to addSubItems(item)
:
<form [formGroup]="orderForm">
...
<div formArrayName="items" *ngFor="let item of orderForm.controls.items.controls; let i = index;">
...
<input type="button" value="subAdd" (click)="addSubItems(item)">
</div>
...
</form>
addSubItems(item: FormGroup): void {
this.subItems = item.get('subItems') as FormArray;
var newSubItem = {
'subname': 'value6'
}
this.subItems.push(this.createSubItem(newSubItem));
}
So, no need to find item by index: var a = this.orderForm['controls']['items']['controls'][_index] as FormGroup;
, because you are already can pass item: FormGroup
StackBlitz Demo